"owl-carousel-o" not proper working with model in angular 11 - javascript

I'm using <owl-carousel-o> with bootstrap model.
here problem like below
When click on image , model will be open but data not display properly at first time after pressing f3,f10,f11,f12 data will be displayed successfully. it is working properly while not using model and also loading data perfectly. It's not taking time in loading data.
Data is displayed only after pressing f3,f10,f12,f11 function key.
I thinks its creating issue due to popper.min.js or jquery.min.js
but they are compulsory for opening model
I also tried with tether.min.js but getting same problem.
At first time model look like :
After pressing function key image look like :
Modal Code:
<div [style.display]="showModal ? 'block' : 'none'" class="modal" id="imagemodal" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="row">
<div class="container d-flex justify-content-center">
<div class="container d-flex justify-content-center">
<div class="card" style="width: 28rem;" id="mcard">
<div class="card-header bg-transparent border-bottom-0">
<button (click)=" hide()" type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
</button>
</div>
<owl-carousel-o [class.owl-refreshed]="refresh" [options]="customOptions" #owlElement>
<ng-container *ngFor="let img of slidesstore">
<ng-template carouselSlide [id]="img.id">
<img style="height: 260px;width:100%;object-fit: cover;"
src='{{"assets/images/" + img.image}}' [alt]="img.name" [title]="img.name"
data-hash="five" />
<div class="card-body">
<p>{{img.id}}</p>
<h5 class="card-title">{{img.name}} </h5>
<p class="card-text">{{img.description}}</p>
</div>
</ng-template>
</ng-container>
</owl-carousel-o>
</div>
</div>
</div>
</div>
</div>
Angular code:
#ViewChild('owlElement', {static: true}) owlElement: CarouselComponent;
customOptions: OwlOptions = {
loop: false,
mouseDrag: true,
touchDrag: true,
pullDrag: false,
dots: false,
navSpeed: 700,
navText: ['&#8249', '›'],
responsive: {
0: {
items: 1,
},
400: {
items: 1,
},
740: {
items: 1,
},
940: {
items: 1,
}
},
nav: true
}
show(id: number) {
this.owlElement.to(id + "");
this.owlElement.options = this.customOptions;
this.refresh = true;
}
Can anyone please suggest me why it's happened ? How can I solved this problem?
I attached code in CodeSandBox . I'm new with codesandbox so I don't have idea how I add jquery.min.js, popper.min.js and bootstrap.min.js in angular.cli. I added dependency in it. and also don't have idea how to add appRoutingModule so I added code in app.component.ts but In original project it's inside home component.
Answer would be appreciated.
Thanks in advance.

An alternative: You can achieve the same (Carousel inside a Modal) using Angular Bootstrap's Modal and Carousel:
HTML:
<ng-template #content let-modal>
<div class="modal-header">
<h4 class="modal-title" id="modal-slide-show">Slide Show</h4>
<button
type="button"
class="close"
aria-label="Close"
(click)="modal.close()"
>
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<ngb-carousel *ngIf="slidesStore" [activeId]="activeSlideId">
<ng-container *ngFor="let slide of slidesStore">
<ng-template ngbSlide [id]="slide.id">
<img
src="{{ 'assets/images/' + slide.image }}"
[alt]="slide.name"
[title]="slide.name"
style="height: 200px; width: 100%; object-fit: cover"
/>
<div class="card-body text-center">
<p>{{ slide.id }}</p>
<h5 class="card-title">{{ slide.name }}</h5>
<p class="card-text">{{ slide.description }}</p>
</div>
</ng-template>
</ng-container>
</ngb-carousel>
</div>
</ng-template>
Component:
constructor(private modalService: NgbModal, config: NgbCarouselConfig) {
config.showNavigationArrows = true;
config.showNavigationIndicators = true;
config.interval = 5000; // make it 0 to stop auto slide
config.animation = true;
config.keyboard = true;
}
activeSlideId = ''; // used to dynamically set the slide id
slidesStore = [
{
id: '39',
name: 'Nature Photography',
description:
'Natural photography comprises of pictures ...',
image: '1613460415834_nature-photography.jpg',
createdAt: 1613730219987,
views: 165,
},
...
]
show(id: number | string, i: number) {
this.openModal(this.content);
this.activeSlideId = id + ''; // set active slide id to start from
}
For more details and options check Modal and Carousel.

Related

How to use a loop inside a slick slider in Vue.js

I'm using vue-slick link https://www.npmjs.com/package/vue-slick inside a bootstrap modal and when i use a v-for loop to loop through the items it display's this.
Here's a snippet of my code
import Slick from 'vue-slick';
export default {
props: ['vehicleRequest'],
components: {'slick': Slick},
data() {
return {
vehicle: {
model: '',
licensePlate: '',
type: '',
currentMileage: '',
Availability: '',
imageUrl: ''
},
vehicles: [],
slickOptions: {
infinite: true,
slidesToShow: 5,
slidesToScroll: 3,
},
}
},
mounted() {
console.log("vehicleRequestId: " + JSON.stringify(this.vehicleRequest));
},
methods: {
updated() {
this.reInit();
},
reInit() {
this.$refs.slickone.reSlick();
},
reserveVehicle() {},
allocateVehicle() {},
getVehicleRequest(id) {},
approveOnline() {
console.log("approve online!");
},
approveOffline() {
console.log("approve offline!");
},
declineRequest() {
$('#declineRequest-Modal').modal('hide');
console.log("vehiclerequest: " + this.vehicleRequest);
console.log("declined");
},
viewVehicle(vehicles) {
let self = this;
self.vehicles = vehicles
$('#viewVehicle').modal('show');
}
}
}
<div
class="modal fade"
id="viewVehicle"
tabindex="-1"
role="dialog"
aria-labelledby="exampleModalCenterTitle"
aria-hidden="true"
>
<div class="modal-dialog modal-lg modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalCenterTitle">{{vehicle.licensePlate}}</h5>
<button
type="button"
class="close"
data-dismiss="modal"
aria-label="Close"
>
<i
class="fas fa-times-circle"
aria-hidden="true"
style="font-size:20px;color: #6e6f6c;"
></i>
</button>
</div>
<div class="modal-body">
<slick ref="slickone" :options="slickOptions">
<div v-for='vehicle in vehicles' :key="vehicle.id">
<img :src="vehicle.vehicle_image_url">
</div>
</slick>
</div>
<div class="col-md-10 mx-auto mb-4">
<div class="row">
<div class="col-md-6">
<div class="w-100">
<button
type="button"
style="margin-left: 25%; padding-left: 20px; padding-right: 20px;"
id="alternativeVehicle"
#click="allocateVehicle()"
class="unicef-btn unicef-reset small-button"
>ALLOCATE ALTERNATIVE VEHICLE</button>
</div>
</div>
<div class="col-md-6">
<div class="w-100">
<button
type="button"
style="margin-left: -7%;"
#click="reserveVehicle()"
id="reserve"
class="unicef-btn unicef-primary small-button"
>RESERVE</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
What could be the problem ?
Sorry guys I was too busy that I hadn't got time to post the above solution anyway I've figured a way to do it although the css styling needs polishing but it still solves what I wanted. What I did was to create property in data called currentIndex and also a function called current vehicle in the computed property. Then I looped the [currentIndex] to get the currentVehicle
computed:{
currentVehicle: function(){
return this.vehicles[Math.abs(this.currentIndex) % this.vehicles.length];
},
},
So the currentVehicle() returns the index of the vehicle in view.
Here's a working one
https://jsfiddle.net/nelsonk/ka01zvtm/

How to determine if a record with a specific value exists in an array from a MSSQL api call using javascript

apologies if this is crazy simple or has been answered a million times before. I just don't seem to be able to make any sense of the other Q&A threads I've been reading.
I am trying to work out how to determine if an array has a particular value in one of it's fields accross all of the rows. In other words, I just want it to ask if there is a "preQualTypeID" of 1 in any of the rows, and if not, I'm getting it to hide a part of the modal.
here is the HTML code for the modal:
<div class="modal fade hide" id="preQualModal" tabindex="-1" role="dialog" aria-labelledby="preQualsModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title" id="preQualsModalLabel">
<i class="fas fa-graduation-cap"></i>
<span>Prerequisite Qualifications</span>
</h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="col-12">
<div class="d-none" id="preQual_AccedemicDetails">
<div class="row pt-1 pb-3">
<div id="preQual_Academic">#*API data goes here*#</div>
</div>
</div>
<div class="d-none" id="preQual_AccessDetails">
<div class="row pt-1 pb-3">
<div id="preQual_Access">#*API data goes here*#</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
And here is the Javascript that I'm trying to implement:
$(function () {
$('#preQualModal').modal({
keyboard: true,
backdrop: "static",
show: false
}).on('show.bs.modal', function () {
var url = "/api/PreQualViewData/";
var qualId = $(event.target).closest('td').data('id');
$.get(url + qualId, function (data) {
var accedemicExist = data.some(function (data) { data.preQualTypeID === 1 });
if (accedemicExist == true) {
$('#preQual_AccedemicDetails').removeClass('d-none');
};
});
});
});
The main thing that I can't get to work is this bit:
var accExist = data.some(function (data) { data.preQualTypeID === 1 });
It always results in "False" and I'm guessing it is an issue with my sytax. When I debug, it says that the "data.preQualTypeID" is undefined, so I'm guessing I've done this wrong, but I don't know where to start. I'm not experienced in Javascript and I find the language a bit confusing.
The API is being built by an ASP controller and looks like this (I've taken out some of the detail to make it easier to read):
[{"qualification":"Graduate Management Training Scheme","level":7,"preQualTypeID":2},
{"qualification":"Degree","level":6,"preQualTypeID":1},
{"qualification":"A Levels","level":3,"preQualTypeID":1},
{"qualification":"GCSEs","level":2,"preQualTypeID":1}]
If anyone can point me in the right direction, I'd be very greatful. Will update with the implementation and vote up those that help.
Thanks
Please let me know if I need to give anymore information.
You can use filter to check if data which received from backend in ajax has preQualTypeID = 1 or not depending on this removeClass .
Demo Code :
var data = [{
"qualification": "Graduate Management Training Scheme",
"level": 7,
"preQualTypeID": 2
},
{
"qualification": "Degree",
"level": 6,
"preQualTypeID": 1
},
{
"qualification": "A Levels",
"level": 3,
"preQualTypeID": 1
},
{
"qualification": "GCSEs",
"level": 2,
"preQualTypeID": 1
}
];
//filter json aray
var accedemicExist = $(data)
.filter(function(i, n) {
return n.preQualTypeID === 1; //check if prequaltypeid=1
});
//if length > 0 exist
if (accedemicExist.length > 0) {
console.log("it exist do something")
//do something
} else {
console.log("not there sorry")
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Javascript not triggering on modal open with Twig Template

Note: I've tried the various solutions found online for my issue, but none of them have worked.
I am trying to pass content from a table where each row has its own button to edit the content in that row. The button opens a Twitter Bootstrap dropdown, which has two buttons, one being the "Edit" button. The edit button opens a modal which has a text-area input. I want the text-area to have the current text present in the table for editing. I am using PHP with Symfony for the forms and Twig for the page rendering.
the button that triggers the modal
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<button class="btn btn-sm dropdown-item edit-button" data-toggle="modal" data-target="#announcementEditModal" data-id="{{ announcement.id }}" data-content="{{ announcement.content }}" type="button">
<div class="announcement-actions">
<span class="fas fa-pencil-alt"></span> Edit announcement
</div>
</button>
The modal
<div class="modal fade" id="announcementEditModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header announcement-header">
<h5 class="modal-title" id="exampleModalLabel"><span class="fas fa-edit"></span> Edit new announcement</h5>
</div>
<div class="announcement-card-header card m-3 border-0">
<div class="announcement-card-header card-body border-0 p-1">
<span class="fa fa-info-circle fa-lg header-icon"></span>
<h5 class="align-header">ANNOUNCEMENT TEXT</h5>
</div>
<div class="announcement-card-body modal-body card border-0">
{{ form_start(editForm) }}
<div class="announcement-card-body">
<label for="exampleInputEmail1">ANNOUNCEMENT (SUPPORTS MARKDOWN)</label>
<textarea class="form-control" id="announcementText" rows="5" name="content"></textarea>
</div>
</div>
</div>
<div class="card-footer border-0 bg-white pt-0">
<div>
{{ form_widget(editForm.edit, {'left_icon': 'fas fa-check'}) }}
<button type="button" class="btn btn-light" data-dismiss="modal" aria-label="Close">
Cancel
</button>
</div>
</div>
{{ form_end(editForm) }}
</div>
</div>
</div>
The JavaScript
<script type="text/javascript">
$(".edit-button").click(function(){
var content = $(this).data("content");
alert(content);
});
$('#announcementEditModal').on('shown.bs.modal', function () {
alert("modal open");
document.getElementById("#announcementText").val(content);
})
</script>
The alert("modal open") does not fire.I have tried'shown.bs.modal'and'show.bs.modal'`. I'm using Bootstrap 4.12
EDIT: Solution: Once I moved the JS to an announcements.js file where I was doing some stuff with my forms the trigger works.
It appears you either have an incomplete html code or have not shared it all with us.
dropdown-menu does not have a closing div.
wrap dropdown-menu inside dropdown or btn-group.
var content will not be available inside your shown.bs.modal function, so declare it globally, not a very good advice but for simplicity sake.
Fix Javascript error, since you are using jQuery, use it.
document.getElementById("#announcementText").val(content); // val is not function
Replace with
document.getElementById("#announcementText").value = content;
$("#announcementText").val(content); // or jQuery way
And here is the fiddle: https://jsfiddle.net/7onyuw9f/1/
Attempt 2
Below is an example of revealing module pattern to show how you can avoid global variables and also a lot cleaner. You can read more about this pattern here
// Revealing Module Pattern
var MyProject = MyProject || {}; // Your global object
MyProject.Modal = function() { // Namespacing to Modal
var content = ""; // now content is local to this function;
var onEditClick = function() {
$(".edit-button").click(function() {
content = $(this).data("content");
alert(content);
});
};
var onModalShow = function() {
$('#announcementEditModal').on('shown.bs.modal', function() {
alert("modal open");
// $("#announcementText").val(content); <-- jQuery way
document.getElementById("announcementText").value = content;
});
};
var init = function() {
onEditClick();
onModalShow();
};
return {
init: init // expose this for other functions to call
}
}();
$(document).ready(function() {
MyProject.Modal.init();
});
And the fiddle https://jsfiddle.net/x28s3uc9/1/

Dynamic Modal Using index as ID VueJS

Hoping someone can help.
This is my first time using Vue and I have been asked to create a teams page which pulls data from a list, groups the names by team name in an array and displays them in card format. I have managed to do all this, however when the cards are clicked I'm looking to have all the team members and their role (e.g developer, product manager etc) display in a modal along with the team image
I have used the index as the ID for each card which is working fine but I am unsure as to how to pass this to the modal to display the correct members for each team when the card is clicked. I have tried various methods I've found on here but none seem to relate exactly to what I'm doing and my lack of Vue knowledge is hindering me as I can do this easily with normal HTML/JS.
It's also probably worth mentioning that due to work PC permissions and the fact this is being built on SharePoint I am having to use the Vue CDN and implement this in 1 HTML file rather than using components.
Many Thanks in advance and I hope this makes sense
Here is my HTML:
<div class="container">
<h1 class="page-heading">MEET<span style="color:#ff0000">IN</span>G THE TEAM</h1>
<p class="intro-text">This is a chance for you to tell your Country and the other teams who you are and what you stand for. You’ll
need a team name, team mascot image, who’s in your team and what you want to say to the world.</p>
<br>
<button class="btn btn-outline-light" type="button" role="button" data-target="#create-modal" data-toggle="modal" id="create-team">Create a New Team</button>
<button class="btn btn-outline-light" type="button" role="button" data-target="#create-modal" data-toggle="modal" id="update-team">Update Your Team</button>
<div class="row" id="team-cards">
<div class="col-md-4" v-for="(team, index) in teams" :key="team[0].teamname" v-if="team[0].teamname !== 'No Team'">
<a href="'#teamModal' + index" data-toggle="modal">
<div class="card" v-bind:id="index">
<img v-bind:src="teammate.teamimage" class="card-img-top" v-for="teammate in team" v-if="teammate.teamimage !== null" :key="teammate.teamimage">
<div class="card-body">
<h5 class="card-title"><strong>{{ team[0].teamname }}</strong></h5>
<p class="card-text" v-for="teammate in team" v-if="teammate.teamdescription !== null" :key="teammate.teamdescription">{{ teammate.teamdescription }}</p>
</div>
<div class="card-footer">
<img class="group-image" v-for="teammate in team" v-if="teammate.hackertype !== 'Developer'" :key="teammate.hackertype" src="https://community.global.hsbc/sites/DigiHub/SiteAssets/hub_assetts/Hack%20Teams/Images/red%20group.png">
<!-- <img class="group-image" v-for="teammate in team" v-else-if="teammate.hackertype !== 'Product Manager' || teammate.hackertype == 'Developer'" :key="teammate.hackertype" src="https://community.global.hsbc/sites/DigiHub/SiteAssets/hub_assetts/Hack%20Teams/Images/yellow%20group.png"> -->
<!-- <img class="group-image" v-for="teammate in team" v-if="teammate.hackertype == 'Developer' || teammate.hackertype == 'Product Manager'" :key="teammate.hackertype" src="https://community.global.hsbc/sites/DigiHub/SiteAssets/hub_assetts/Hack%20Teams/Images/green%20group.png"> -->
<a href="https://community.global.hsbc/sites/DigiHub/SitePages/Hack-Chat.aspx" target="_blank">
<img class="chat-image" src="https://community.global.hsbc/sites/DigiHub/SiteAssets/hub_assetts/Hack%20Teams/Images/chat.png">
</a>
</div>
</div>
</a>
</div>
</div>
</div>
<!-- Team Modal -->
<div class="modal fade" v-bind:id="['teamModal'+index]" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"><b>{{ team[0].teamname }}</b></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<br>
<div class="modal-body" v-for="teammate in team">
<p>{{ teammate.name }}</p>
<p>{{ teammate.hackertype }}</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
And my VueJS:
$(function () {
var appTeamCards = new Vue({
el: '#app-teams',
data: {
teams: [],
teamMembers: [],
},
mounted: function() {
this.getTeams();
},
methods: {
getTeams: function() {
var self = this;
$.ajax({
url: '/sites/DigiHub/_api/web/lists/getbytitle(\'global-hackathon-reg\')/items?$orderby=Modified desc',
method: "GET",
headers: {
"Accept": "application/json;odata=verbose"
},
success: function (data) {
var posts = data.d.results;
readData(posts);
console.log(self.teams);
},
});
function readData(data) {
self.teams = groupBy(data, "teamname");
};
function groupBy(collection, property) {
var i = 0, val, index,
values = [], result = [];
for (; i < collection.length; i++) {
val = collection[i][property];
index = values.indexOf(val);
if (index > -1)
result[index].push(collection[i]);
else {
values.push(val);
result.push([collection[i]]);
}
}
return result;
}
},
}
});
$('#update-team').click(function(){
$("#new-member-form").hide();
$("#reg-another-update").show();
$("#update-form").show();
});
$('#create-team').click(function(){
$("#new-member-form").show();
$("#update-form").show();
$("#reg-another-update").hide();
});
$('#reg-another-update').click(function(){
$("#new-member-form").show();
$("#reg-another-update").hide();
$("#update-form").hide();
});
$('#submit-team-btn').click(function(){
$("#update-form").attr("disabled", "disabled");
});
});
It seems I had the right solution but the syntax was slightly wrong. I have made the following amendments and my code now works as expected.
The card anchor reference should be written as follows:
<a :href="'#teamModal' + index" data-toggle="modal">
Modal ID:
<div class="modal fade" :id="'teamModal' + index" v-for="(team, index) in teams" :key="team[0].teamname" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">

Uncaught Error: You cannot apply bindings multiple times to the same element

How could I combine the two models which i have kept for two different purpose. One is to for file upload and the other is for render data from different object.Below is the respective html and JS i tried.
HTML section
<div class="well" data-bind="fileDrag: fileData">
<div class="form-group row">
<div class="col-md-6">
<img style="height: 125px;" class="img-rounded thumb" data-bind="attr: { src: fileData().dataURL }, visible: fileData().dataURL">
<div data-bind="ifnot: fileData().dataURL">
<label class="drag-label">Drag file here</label>
</div>
</div>
<div class="col-md-6">
<input type="file" data-bind="fileInput: fileData, customFileInput: {
buttonClass: 'btn btn-success',
fileNameClass: 'disabled form-control',
onClear: onClear,
}" accept="application/pdf,image/*">
</div>
</div>
</div>
<button class="btn btn-default" data-bind="click: debug">Upload</button>
</div>
<div id="notification" style="display: none;">
<span class="dismiss"><a title="dismiss this notification">X</a></span>
</div>
<!-- Collapsible Panels - START -->
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Plan Details</h3>
</div>
<div class="panel-body">
<span class="glyphicon glyphicon-plus clickable" id="addPlanBtn"></span>
<span class="glyphicon glyphicon-remove clickable" id="removePlanBtn"></span>
<span class="glyphicon glyphicon-edit clickable" id="editPlanBtn"></span>
<table id="docsDataTable" class="table table-striped display" width="100%">
<thead>
<tr>
<th></th>
<th>Contract Document ID</th>
<th>Contract ID</th>
<th>Document Name</th>
<th>File Path</th>
<th>Comments</th>
</tr>
</thead>
</table>
<div class="modal fade" id="notificationDialog" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" \>×</button>
<h4 class="modal-title">Notification</h4>
</div>
<div class="modal-body" id="notificationBody">
</div>
<div class = "modal-footer">
<button type = "button" class = "btn btn-primary" data-dismiss = "modal">
Ok
</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="confirmBox" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" \>×</button>
<h4 class="modal-title">Confirmation</h4>
</div>
<div class="modal-body" id="confirmBody">
Selected rows will be made inactive.
</div>
<div class = "modal-footer">
<button type = "button" class = "btn btn-default" data-dismiss = "modal" id="confirmNoBtn">
Cancel
</button>
<button type = "button" class = "btn btn-primary" data-dismiss = "modal" id="confirmYesBtn">
Ok
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Javascript section to bind the data
var dataset;
var docsModel;
var docsTable;
var vasTypes;
$(function(){
var viewModel = {};
viewModel.fileData = ko.observable({
dataURL: ko.observable(),
// base64String: ko.observable(),
});
viewModel.onClear = function(fileData){
if(confirm('Are you sure?')){
fileData.clear && fileData.clear();
}
};
viewModel.debug = function(){
window.viewModel = viewModel;
//console.log(ko.toJSON(viewModel));
fileUpload(viewModel);
debugger;
};
ko.applyBindings(viewModel);
});
$(document).ready(function(){
docsModel = new $.cordys.model({
context: document.getElementById("addPanelForm"),
objectName: "CONTRACT_DOCUMENT",
fields: ["CONTRACT_DOCUMENT_ID" , "CONTRACT_ID" , "DOCUMENT_NAME" , "FILE_PATH" , "COMMENTS"],
defaults: {
namespace: "http://services.vw.com/lpms/1.0/wsapp"
},/*
update: {
method: "UpdatePlanVas"
},*/
read: {
method: "GetContractDocumentObjectsForContractId",
parameters: {
CONTRACT_ID: "CONTRACT_1000"
},
}
});
GetContractDocumentObjectsForContractId();
docsTable = $('#docsDataTable').DataTable({
data: dataset,
columnDefs: [ {
orderable: false,
className: 'select-checkbox',
defaultContent: "",
targets: 0},
{ data: "CONTRACT_DOCUMENT_ID",
targets: 1,
visible: false},
{ data: "CONTRACT_ID",
targets: 2},
{ data: "DOCUMENT_NAME",
targets: 3},
{ data: "COMMENTS",
targets: 5},
{ data: "FILE_PATH",
targets: 4}],
select: {
style: 'multi',
selector: 'td:first-child'
},
order: [[ 1, 'asc' ]],
"searching": false,
"lengthChange": false
});
});
function fileUpload(data){
dataObject=ko.toJS(viewModel);
fileName=dataObject.fileData.file.name;
fileContent=dataObject.fileData.dataURL.split(',')[1];
$.cordys.ajax({
method: "WriteFile",
parameters: {
filename: fileName,
encoded: "true",
data:fileContent
},
namespace:"http://schemas.cordys.com/1.0/ac/FileConnector",
dataType: "* json",
async: false,
success: function(e){
$.notify("Yeah ! File Uploaded", "success");
}
});
}
You're getting the error
You cannot apply bindings multiple times to the same element
Because Knockout only permits one view-model to be bound to a DOM element.
In your case, you need to somehow combine the two view-models into one. While you could simply add the properties from one view-model into the other, perhaps creating a third view-model with a new name so you can continue using the original form of these view-models elsewhere, my suggestion would be to create a new super view-model, and reference the two existing view-models as properties on this new view-model.
At this point I would normally create an example from the code in the OP but in this case, as #Jeroen has pointed out, it's rather difficult to make out what's going on in the OP. As far as I can see, there's only one view-model in there while your question revolves around having two view-models. So the following example is unfortunately very generic.
var ViewModel1 = function() {
var self = this;
self.obs1_1 = ko.observable();
self.obs1_2 = ko.observableArray([]);
// some initialisation stuff
},
ViewModel2 = function() {
var self = this;
self.obs2_1 = ko.observable();
self.obs2_2 = ko.observableArray([]);
// some initialisation stuff
},
SuperViewModel = function() {
var self = this;
self.vm1 = new ViewModel1();
self.vm2 = new ViewModel2();
// some initialisation stuff
};
You would then instantiate and data-bind SuperViewModel, and reference the observables like so
<input type="text" data-bind="textInput: vm1.obs1_1" />
<div data-bind="foreach: vm1.obs1_2">
<span data-bind="html: $data"></span>
</div>
or to make typing a little bit easier
<!-- ko with: vm1 -->
<input type="text" data-bind="textInput: obs1_1" /> <!-- this time without "vm1." -->
<div data-bind="foreach: obs1_2"> <!-- this time without "vm1." -->
<span data-bind="html: $data"></span>
</div>
<!-- /ko -->
You now have a single view-model, SuperViewModel, referencing your unchanged existing view-models. This solution allows you to leave existing JavaScript and views while offering an easy method of data-binding the functionality of multiple view-models inside a single view-model.
It's technically possible to achieve a similar result by doing some referencing at the prototype level, but that could quickly cause complications and the only advantage would be saving you from typing the name of a property.

Categories

Resources