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

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/

Related

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

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.

Image not loading in nested route vue js

I've created a custom component for my app to select multiple images for product:
<template>
<!-- Image modal -->
<div
class="modal fade"
id="gallery-multi"
tabindex="-1"
role="dialog"
aria-labelledby="galleryLabel"
aria-hidden="true"
>
<div class="modal-dialog modal-dialog-centered modal-lg " role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="gallery">Gallery</h5>
<button type="button" class="close" #click="closeModal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<vue-select-image
:dataImages="dataImages"
:is-multiple="true"
#onselectmultipleimage="onSelectMultipleImage"
:h="'90'"
:w="'140'"
></vue-select-image>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" #click="closeModal()">Close</button>
</div>
</div>
</div>
</div>
</template>
<script>
import VueSelectImage from "vue-select-image";
import "vue-select-image/dist/vue-select-image.css";
export default {
name: "selectMultiImg",
data() {
return {
multiID:[],
dataImages: [
{
id: "",
src: "",
alt: ""
}
]
};
},
methods: {
closeModal() {
$("#gallery-multi").modal("hide");
},
onSelectMultipleImage: function(data) {
this.multiID = data.id;
this.$emit('multiImg', this.multiID);
}
},
components: { VueSelectImage },
mounted() {
axios.get("/api/gallery").then(response => {
this.dataImages = response.data.map((obj, index) => {
return {
id: obj.id,
src: obj.thumb,
alt: obj.name
};
});
});
}
};
</script>
I'm using this component in other routes as well (main routes) like:
{
path: "/product-category",
component: require("./components/product/Category.vue")
},
and it runs smoothly in main routes. But I'm having trouble in nested route:
{
path: "/product/create",
component: require("./components/product/Create.vue"),
},
The problem is image doesn't load in nested route.
In the above picture the original path of the image is src="img/thumb_dcb7d855594bb92d2fd83108e8a2620e.jpg" but in highlighted section of the path is http://localhost:3000/product/img/thumb_dcb7d855594bb92d2fd83108e8a2620e.jpg
Which is added by the vue itself (I suppose). Furthermore there is no error in console also.
Can anyone help me figure out what is causing this and its possible solution ?
It not Vue added this URL.
Use absolute path to images.
Example:
src: '/' + obj.thumb

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">

Vue.js Display call one component from another component

I have 2 components:
Vue.component('repo-button', {
props:["check_in_id", "repo_id"],
template: '#repo-button',
methods: {
fetchRepo: function() {
url = window.location.href.split("#")[0] + "/check_ins/" + this.check_in_id + "/repositionings/" + this.repo_id + ".json"
cl(url)
cl(this)
var that;
that = this;
$.ajax({
url: url,
success: function(data) {
cl(data)
that.showRepo();
}
})
},
showRepo: function() {
// what do I put here to display the modal
}
},
data: function() {
var that = this;
return {
}
}
});
Vue.component('repo-modal', {
template: "#repo-modal",
data: function() {
return {
status: 'none'
}
}
});
var repositionings = new Vue({
el: "#repo-vue"
});
...and my view consists of a button and a modal. I'd like the button to call fetchRepo on the repo-button component and display the modal (change its status property from none to block.
<script type="text/x-template" id="repo-button">
<div class='socialCircle-item success'>
<i class='fa fa-comment'
#click="fetchRepo"
:data-check_in='check_in_id'
:data-repo='repo_id'>
</i>
</div>
</script>
<script type="text/x-template" id="repo-modal">
<div v-bind:style="{ display: status }" class="modal" id="vue-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-client_id="<%= #client.id %>">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title"></h4>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<button type="button" class="btn btn-danger btn-simple" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</script>
<div id="repo-vue">
<div is="repo-modal"></div>
<div is="repo-button" repo_id="<%= ci.repositioning.id %>" check_in_id="<%= ci.id %>"></div>
</div>
Props down, events up
In Vue.js, the parent-child component relationship can be summarized
as props down, events up. The parent passes data down to the child via
props, and the child sends messages to the parent via events.
In particular, if the state of a component needs to be controlled externally (by a parent or sibling), that state should be passed in as a prop from the parent. Events indicate to the parent that the state should be changed.
Your modal's state is controlled by events in itself and in a sibling component. So the state lives in the parent, and is passed to the modal as a prop. Clicking the modal Close button emits a (custom) hidemodal event; clicking the sibling component's comment icon emits a showmodal event. The parent handles those events by setting its showRepoModal data item accordingly.
Vue.component('repo-button', {
template: '#repo-button',
methods: {
showRepo: function() {
this.$emit('showmodal');
}
}
});
Vue.component('repo-modal', {
template: "#repo-modal",
props: ["show"],
computed: {
status() {
return this.show ? 'block' : 'none'
}
},
methods: {
hideRepo() {
this.$emit('hidemodal');
}
}
});
var repositionings = new Vue({
el: "#repo-vue",
data: {
showRepoModal: false
}
});
.socialCircle-item i {
cursor: pointer;
}
<link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script>
<template id="repo-button">
<div class='socialCircle-item success'>
<i class='fa fa-comment'
#click="showRepo"
>
</i>
</div>
</template>
<template id="repo-modal">
<div v-bind:style="{ display: status }" class="modal" id="vue-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" >
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title"></h4>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<button type="button" #click="hideRepo" class="btn btn-danger btn-simple" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</template>
<div id="repo-vue">
<div is="repo-modal" :show="showRepoModal" #hidemodal="showRepoModal = false"></div>
<div is="repo-button" #showmodal="showRepoModal = true"></div>
</div>

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