create observables dynamically and show it in html ,knockout? - javascript

HTML :-
<div class="row" style="margin-left: 10px;" data-bind="foreach: {data: data, as: 'data1'}">
<span style="color: red; display: none;" data-bind="attr:{'id':data1.mandatory!=0?'id'+data1.dynamicid:''},text: 'You have selected ' +app.vm.observables.totalSelected()+ ' Observation areas. Please restrict to only 2.'"></span>
</div>
here the observable is same for every div element id so value is showing same how to do it dynamically?
JAVASCRIPT :-
`$('#id'+dynamicid+' input:checkbox.paramValues:checked').each(function(e){
DataImprove++;
});`
if(DataImprove>2){
vm.observables.totalSelected(DataImprove);
}
Need to create observables dynamically based on the div element ids and show it in the frontend HTML.

I'm not entirely sure I understand what you are trying to do, but hopefully this helps
I think it would make sense to move some of the functionality out out the view and into a viewModel
var externalData = [{
mandatory: false,
dynamicid: 1,
}, {
mandatory: false,
dynamicid: 2,
}, {
mandatory: 1,
dynamicid: 3,
}, {
mandatory: false,
dynamicid: 4,
}];
function ViewModel() {
var self = this;
self.data = ko.observableArray([]);
self.totalSelected = ko.pureComputed(function() {
return self.data().filter(function(i) {
return i.selected() === true;
}).length;
});
self.selectedText = ko.pureComputed(function(){
return 'You have selected ' + self.totalSelected() + ' Observation areas.';
});
var mappedData = externalData.map(function(item) {
return {
mandatory: item.mandatory,
dynamicid: item.dynamicid,
selected: ko.observable(false),
mandatoryStatus: item.mandatory == true ? 'mandatory' : ''
};
});
self.data(mappedData);
}
var vm = new ViewModel();
ko.applyBindings(vm);
.mandatory {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<span data-bind="text: selectedText"></span>
<ul data-bind="foreach: {data: data, as: 'data1'}">
<li data-bind="class: mandatoryStatus">
<label data-bind="text: dynamicid"></label>
<input type="checkbox" data-bind="checked: selected" />
</li>
</ul>

Related

How do I toggle a knockout foreach div individually without adding more html?

I used the foreach method to create markup foreach item in an observable array to create a treeview.
output example
category name1
content
content
category name 2
content
content
when I click on the category name I want just its content to show/hide, currently when I click on the category name it shows and hides all the categories.
var reportFilters = [
{ Text: "Campaign", Value: primaryCategories.Campaign },
{ Text: "Team", Value: primaryCategories.Team },
{ Text: "Agent", Value: primaryCategories.Agent },
{ Text: "List", Value: primaryCategories.List },
{ Text: "Inbound", Value: primaryCategories.Inbound },
{ Text: "Daily", Value: primaryCategories.Daily },
{ Text: "Services", Value: primaryCategories.Services },
{ Text: "Occupancy", Value: primaryCategories.Occupancy },
{ Text: "Data", Value: primaryCategories.Data }
];
self.showCategory = ko.observable(false);
self.toggleVisibility = function (report) {
var categoryName = report.PrimaryReportCategory;
var categoryContent = report.ID;
if (categoryName == categoryContent ) {
self.showCategory(!self.showCategory());
};
}
<div class="report-category-treeview" data-bind="foreach: $root.categories, mCustomScrollBar:true">
<ul class="column-list" >
<li class="report-category-heading" data-bind="click: $root.toggleVisibility"><span class="margin-top10" ><i class="fas fa-chevron-down"></i> <span class="report-category-name" data-bind="text: categoryName"></span></span></li>
<li id="panel" class="report-category-container" data-bind="foreach: reports, visible: $root.showCategory">
<div class="column-list-item" data-bind="click: $root.report_click, css: { 'selected': typeof $root.selectedReport() != 'undefined' && $data == $root.selectedReport() }">
<span class="column-list-text" data-bind="text: ReportName"></span>
</div>
</li>
</ul>
</div>
currently, when I click on the category name, it shows and hides all the
categories.
It's because showCategory is your single observable responsible for showing\hiding. What you really want is one show\hide observable per category.
I'm not sure how your entire data model looks like, but since you specifically asked about categories, then you should create a category view model, and probably some container view model, which I'll name here master:
var categoryVM = function (name) {
var self = this;
self.name = ko.observable(name);
self.isVisible = ko.observable(false);
self.toggleVisibility = function () {
self.isVisible(!self.isVisible());
}
// ... add here your other observables ...
}
// name 'masterVM' whatever you like
var masterVM = function () {
var self = this;
self.categories = ko.observables([]);
// ... probably add here other observables, e.g. 'reports' ...
self.init = function (rawCategories) {
rawCategories.forEach(function (item) {
categories.push(new categoryVM(item.name)); // replace 'name' with your property
}
}
}
var master = new masterVM();
master.init(getCategories()); // pass in your categories from wherever they come from
ko.applyBindings(master);
Then, in your html, this would be your outer foreach:
<div class="report-category-treeview" data-bind="foreach: categories ... />
and your lis (for brevity, I'm ommiting nested tags under your lis):
<li class="report-category-heading"
data-bind="click: toggleVisibility">
<li id="panel" class="report-category-container"
data-bind="foreach: $root.reports, visible: isVisible">

Link div and textbox value on div selection

I am trying to sync div with textbox.
For example, I created 2 nodes i.e Node 1 and Node 2 and when I select node1 and I enter title and location then title and location should sync with Node1 so when I enter title while I have selected node1 then title value should get reflected for node1 and after entering title and location next time when I select node1 then title and location value should be reflected in my textbox.
I created this below Fiddle to demonstrate the problem : http://jsfiddle.net/quk6wtLx/2/
$scope.add = function (data) {
var post = data.nodes.length + 1;
var newName = data.name + '-' + post;
data.nodes.push({ name: newName, nodes: [],selected : false });
};
$scope.tree = [{ name: "Node", nodes: [], selected: false }];
$scope.setActive = function (data) {
clearDivSelection($scope.tree);
console.log(data);
data.selected = true;
};
I am not getting how to do this.
You need to bind the form elements with the data you are appending to the tree.
Check this snippet
var app = angular.module("myApp", []);
app.controller("TreeController", function ($scope) {
$scope.delete = function (data) {
data.nodes = [];
};
$scope.add = function (data) {
var post = data.nodes.length + 1;
var newName = data.name + '-' + post;
data.nodes.push({ name: newName, nodes: [],selected : false, myObj: { name: newName} });
};
$scope.tree = [{ name: "Node", nodes: [], selected: false }];
$scope.setActive = function ($event, data) {
$event.stopPropagation();
$scope.selectedData = data;
clearDivSelection($scope.tree);
data.selected = true;
};
function clearDivSelection(items) {
items.forEach(function (item) {
item.selected = false;
if (item.nodes) {
clearDivSelection(item.nodes);
}
});
}
});
ul {
list-style: circle;
}
li {
margin-left: 20px;
}
.active { background-color: #ccffcc;}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<ul ng-app="myApp" ng-controller="TreeController">
<li ng-repeat="data in tree" ng-include="'tree_item_renderer.html'"></li>
<script type="text/ng-template" id="tree_item_renderer.html">
<div ng-class="{'active': data.selected}" > {{data.myObj.name}}</div>
<button ng-click="add(data)">Add node</button>
<button ng-click="delete(data)" ng-show="data.nodes.length > 0">Delete nodes</button>
<ul>
<li ng-repeat="data in data.nodes" ng-include="'tree_item_renderer.html'" ng-click="setActive($event, data)"></li>
</ul>
</script>
<div style="margin-left:100px;">
Title : <input type="text" ng-model="selectedData.myObj.name" />
Location : <input type="text" ng-model="selectedData.myObj.location" />
</div>
</ul>
You can check the binding documentation for AngularJs and all the possibilities https://docs.angularjs.org/guide/databinding

Knockout foreach array checkboxes are not visually updating

I have a json array that has elements created in a foreach databind.
Then I'm retaining the selected object in that array so that I can have independent "Save Changes" buttons for each object in that array. All of that is working (primarycontactname for example) except the binding for the checkboxes.
<div class="container span8" data-bind="foreach: locationssubscribed">
<div class="well span3" data-bind="click: $parent.selectedLocationSubscribed">
<input type="text" class="span3" data-bind="value: primarycontactname" placeholder="Contact Name.." />
<br />
<div class="checkbox" data-bind="visible: (vendorbringinggifts() === 0 || vendorbringinggifts() === vendorid())">
<input id="chkGiftsAreBeingBrought" type="checkbox" data-bind="checked: giftsarebeingbrought" />
</div>
<button data-bind="click: $root.saveVendorToLocation, enable: needsave, text: needsave() ? 'Save Location Changes' : 'No Changes to Save', css: { 'btn-primary': needsave }" class="btn">Save Location Changes</button>
</div>
</div
The checkboxes load correctly based on the giftsarebeingbrought observable in each array object but when clicking the checkbox the visible check doesn't toggle. Using the debugger I can see that the observable giftsarebeingbrought in the original array and in the selectedLocationSubscribed are toggling on the first click but then do not toggle again on subsequent clicks and the visual checkbox never changes after the initial binding.
{
"locationssubscribed": [
{
"vendortolocationid": 10,
"primarycontactname": "Fake Name1",
"vendorbringinggifts": 0,
"giftsarebeingbrought": false,
"needsave": false
},
{
"vendortolocationid": 11,
"primarycontactname": "Fake Name2",
"vendorbringinggifts": 0,
"giftsarebeingbrought": false,
"needsave": false
},
{
"vendortolocationid": 12,
"primarycontactname": "Fake Name3",
"vendorbringinggifts": 0,
"giftsarebeingbrought": false,
"needsave": false
},
{
"vendortolocationid": 13,
"primarycontactname": "Fake Name4",
"vendorbringinggifts": 0,
"giftsarebeingbrought": false,
"needsave": false
}
],
"selectedLocationSubscribed": {
"vendortolocationid": 12,
"primarycontactname": "Fake Name1",
"vendorbringinggifts": 0,
"giftsarebeingbrought": true,
"needsave": true
}
}
function VendorToLocation(vtl) {
this.vendortolocationid = ko.observable(vtl.VendorToLocationID);
this.primarycontactname = ko.observable(vtl.PrimaryContactName);
this.vendorbringinggifts = ko.observable(vtl.VendorBringingGifts);
this.giftsarebeingbrought = ko.observable(vtl.GiftsAreBeingBrought);
this.needsave = ko.observable(false);
}
function VendorViewModel() {
var self = this;
self.locationssubscribed = ko.observableArray();
self.selectedLocationSubscribed = ko.observable();
self.selectedLocationSubscribed.subscribe(function (ftl) {
if (ftl !== null) {
ftl.needsave(true);
}
});
self.getLocationsAvailable = function (vendorID) {
self.locationsavailable.removeAll();
$.ajax($("#GetLocationsAvailableUrl").val(), {
data: '{ "vendorID":' + vendorID + '}',
async: false,
success: function (allData) {
self.locationsavailable($.map(allData, function (item) { return new LocationsAvailable(item) }));
}
});
}
self.getLocationSubscription = function (vendorID) {
self.locationssubscribed.removeAll();
$.ajax($("#GetLocationSubscriptionUrl").val(), {
data: '{ "vendorID":' + vendorID + '}',
success: function (allData) {
self.locationssubscribed($.map(allData, function (item) { return new VendorToLocation(item) }));
}
});
}
self.saveVendorToLocation = function () {
var url = $("#updateVendorToLocationUrl").val();
var vendorid = self.selectedVendor().vendorid();
var selectedLoc = self.selectedLocationSubscribed();
$.ajax(url, {
data: '{ "vtl" : ' + ko.toJSON(selectedLoc) + '}',
success: function (result) {
if (result === false) {
toastr.error("ERROR!: Either you or a competing vendor has chosen this location since you last loaded the webpage. Please refresh the page.");
} else {
toastr.success("Vendor to location details saved");
selectedLoc.vendortolocationid(result.VendorToLocationID);
self.updateVendorView(); // added 170307 1030 to get vendor contact details to update automatically
self.getActionLog(vendorid);
selectedLoc.needsave(false);
}
}
});
};
}
$(document).ready(function () {
var myViewModel = new VendorViewModel();
ko.applyBindings(myViewModel);
myViewModel.updateVendorView();
myViewModel.getLocationSubscription(curVendorID);
}
The goal is to get the checkbox working correctly. The rest of the textbox based bindings I removed to condense the post have worked correctly for years some I'm now stumped as to what I'm doing wrong with the textbox.
Let me reconfirm, so you're trying to enable the associated button as well as check the checkbox if a user click on an element inside <div class="well span3 ...>".
I put all the suggestions in the code directly.
function VendorToLocation(vtl) {
var self = this;
self.vendortolocationid = ko.observable(vtl.vendortolocationid);
self.primarycontactname = ko.observable(vtl.primarycontactname);
self.vendorbringinggifts = ko.observable(vtl.vendorbringinggifts);
self.giftsarebeingbrought = ko.observable(vtl.giftsarebeingbrought);
self.needsave = ko.observable(vtl.needsave);
// I prefer to put all the logic in here instead of being embedded to the HTML
self.isCheckboxVisible = ko.pureComputed(function(){
return self.vendorbringinggifts() === 0 || self.vendorbringinggifts() === self.vendortolocationid();
});
}
function VendorViewModel() {
var self = this;
self.locationssubscribed = ko.observableArray(
[
new VendorToLocation ({
"vendortolocationid": 10,
"primarycontactname": "Fake Name1",
"vendorbringinggifts": 0,
"giftsarebeingbrought": false,
"needsave": false
}),
new VendorToLocation ({
"vendortolocationid": 11,
"primarycontactname": "Fake Name2",
"vendorbringinggifts": 0,
"giftsarebeingbrought": false,
"needsave": false
}),
new VendorToLocation ({
"vendortolocationid": 12,
"primarycontactname": "Fake Name3",
"vendorbringinggifts": 0,
"giftsarebeingbrought": false,
"needsave": false
}),
new VendorToLocation ({
"vendortolocationid": 13,
"primarycontactname": "Fake Name4",
"vendorbringinggifts": 0,
"giftsarebeingbrought": false,
"needsave": false
})
]
);
// To store the selected location
self.selectedLocationSubscribed = ko.observable();
// To modify selected location, enable the button and modify the checkbox whenever user click on an element that uses this as its click event
self.selectLocationSubscribed = function(data, event) {
if(data !== null) {
self.selectedLocationSubscribed(data);
// If you want to change needsave of other properties to false (disable all other buttons) before that you can do it here
ko.utils.arrayForEach(self.locationssubscribed(), function(location) {
if(data.vendortolocationid() !== location.vendortolocationid()){
location.needsave(false);
location.giftsarebeingbrought(false);
}
});
// code ends here
// And then you modify the selected needsave the selected object to true to enable the button
data.needsave(true);
data.giftsarebeingbrought(true);
}
// To perform the default browser click action
return true;
}
}
$(document).ready(function () {
var myViewModel = new VendorViewModel();
ko.applyBindings(myViewModel);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="container span8" data-bind="foreach: locationssubscribed">
<div class="well span3" data-bind="click: $parent.selectLocationSubscribed">
<input type="text" class="span3" data-bind="value: primarycontactname" placeholder="Contact Name.." />
<br />
<div class="checkbox" data-bind="visible: (vendorbringinggifts() === 0 || vendorbringinggifts() === vendorid())">
<input id="chkGiftsAreBeingBrought" type="checkbox" data-bind="checked: giftsarebeingbrought" />
</div>
<button data-bind="click: $root.saveVendorToLocation, enable: needsave, text: needsave() ? 'Save Location Changes' : 'No Changes to Save', css: { 'btn-primary': needsave }" class="btn">Save Location Changes</button>
</div>
</div>
The click binding prevents the default action. To enable the default action, return true from the event handler. This means you can't directly pass an observable to the click binding.
click: $parent.handleClick
JS:
self.handleClick = function (item) {
// do something with item
return true; // don't prevent default action
}

Identical function using ng-show works to load one controller in Angular JS, but not the another one

I'm creating a page using Angular which has three controllers. They are loaded using ng-show directive. Each controller has a button with ng-click which calls a function. The function is simple it hides one controller and makes the next one visible.
The problem: this function works for one controller, but for some reason it doesn't work for the other one. Precisely, levelsView controller is loaded, but cardsView is not. CardsView becomes visible if I set ng-show to true in HTML page, but not through the function. I've spent a few days trying to find the problem and I can't, please help me to solve this "mystery".
HTML page:
<main>
<div class="bottom-container">
<div ng-controller="rulesCtrl as rulesView" ng-hide="rulesView.gameMetrics.levelsActive || rulesView.gameMetrics.cardsActive"
class="rules">
<p><span class="bold large-text">Rules: </span>Find a pair for the HTML opening and closing tag or match CSS value with a property within given time. <button class="link-button" data="#rulesHide">Read more...</button></p>
<div class="rules-details" id="rulesHide">
<p><span class="bold large-text">HTML: </span>For HTML a pair would be <span class="bold"><div> + </div></span>.</p>
<p><span class="bold large-text">CSS: </span>For CSS an example could be the property <span class="bold">display</span>. It has values: <span class="bold">block, inline, inline-block </span>etc. A pair would be <span class="bold">display + block.</span></p>
<p>The main challange is to find the pairs fast. The harder the level the shorter will be the time given.</p>
</div>
<button class="button btn-start" ng-click="rulesView.showLevels()">Start</button>
</div>
<div ng-controller="levelsCtrl as levelsView" ng-show="levelsView.gameMetrics.levelsActive" class="levels">
<h2>Select Level:</h2>
<button class="button btn-easy" ng-click="levelsView.showCards()">Easy</button>
<button class="button btn-medium">Medium</button>
<button class="button btn-hard">Hard</button>
</div>
<div ng-controller="cardsCtrl as cardsView" ng-show="cardsView.gameMetrics.cardsActive" class="game-field">
<h2>Find the tag pairs on time.</h2>
<span class="fa fa-clock-o fa-lg"></span>
<span class="game-timer">{{ cardsView.timeLeft }}</span>
<span class="game-timer-msg">{{ cardsView.timesUp }}</span>
<div class="flex-container">
<div class="flex-item"
ng-repeat="cardsData in cardsView.data">
{{ cardsData.text }}
</div>
</div>
</div>
</div>
</main>
Factory with data:
(function(){
angular
.module("syntaxPairing")
.factory("gameMetrics", GameMetrics);
GameMetrics.$inject = ["DataService"];
function GameMetrics(DataService){
var gameObject = {
rulesActive: true,
levelsActive: false,
cardsActive: false,
changeVisibility: changeVisibility
};
return gameObject;
function changeVisibility(metric, state){
if(metric === "rulesView"){
gameObject.rulesActive = state;
}else if(metric === "levelsView"){
gameObject.levelsActive = state;
}else if(metric === "cardsView"){
gameObject.cardsActive = state;
}
return false;
}
}
})();
First controller (rulesView.js):
(function(){
angular
.module("syntaxPairing")
.controller("rulesCtrl", RulesController);
RulesController.$inject = ["gameMetrics", "DataService"];
function RulesController(gameMetrics){
var vm = this;
vm.gameMetrics = gameMetrics;
vm.showLevels = showLevels;
function showLevels(){
gameMetrics.changeVisibility("rulesView", false);
gameMetrics.changeVisibility("levelsView", true);
}
}
})();
Second controller (levelsView.js):
(function(){
angular
.module("syntaxPairing")
.controller("levelsCtrl", LevelsController);
LevelsController.$inject = ["gameMetrics", "DataService"];
function LevelsController(gameMetrics){
var vm = this;
vm.gameMetrics = gameMetrics;
vm.showCards = showCards;
function showCards(){
gameMetrics.changeVisibility("levelsView", false);
gameMetrics.changeVisibility("rulesView", false);
gameMetrics.changeVisibility("cardsView", true);
}
}
})();
Third controller (cardsView.js):
(function(){
angular
.module("syntaxPairing")
.controller("cardsCtrl", CardsController);
CardsController.$inject = ["gameMetrics", "DataService", "$timeout"];
function CardsController(gameMetrics, DataService, $timeout){
var vm = this;
vm.data = DataService.cardsData;
vm.timeLeft = 5;
vm.onTimeout = onTimeout;
function onTimeout(){
vm.timeLeft--;
if(vm.timeLeft > 0){
mytimeout = $timeout(onTimeout, 1000);
}else{
vm.timesUp = "The time is up!";
}
}
var mytimeout = $timeout(onTimeout, 1000);
}
})();
DataService:
(function(){
angular
.module("syntaxPairing")
.factory("DataService", DataFactory);
function DataFactory(){
var dataObject = {
cardsData: cardsData
};
return dataObject;
}
var cardsData = [
{
type: "text",
text: "<html>",
selected: null,
correct: null
},
{
type: "text",
text: "</html>",
selected: null,
correct: null
},
{
type: "text",
text: "<header>",
selected: null,
correct: null
},
{
type: "text",
text: "</header>",
selected: null,
correct: null
},
{
type: "text",
text: "<body>",
selected: null,
correct: null
},
{
type: "text",
text: "</body>",
selected: null,
correct: null
},
{
type: "text",
text: "<p>",
selected: null,
correct: null
},
{
type: "text",
text: "</p>",
selected: null,
correct: null
},
{
type: "text",
text: "<script>",
selected: null,
correct: null
},
{
type: "text",
text: "</script>",
selected: null,
correct: null
},
{
type: "text",
text: "<span>",
selected: null,
correct: null
},
{
type: "text",
text: "</span>",
selected: null,
correct: null
}
]
})();
In third controller i.e. cardsCtrl, you are missing gameMetrics. So cardsView.gameMetrics.cardsActive is not changed.
Just add the below line, it works perfectly.
vm.gameMetrics = gameMetrics;
http://jsbin.com/zeredah/edit?html,js,output

Make Angular checkbox unselect

I have requirement where from array i have to create list of checkbox using classes.now again one reset button will be there after clicking on that all selection will be reseted , how to do that thanks
$scope.classList=['Class1','Class2','Class3','Class4'];
$scope.selectedClasses={};
$scope.selectedClasses.usall=false;
$scope.selectedClasses.sall=false;
$scope.selectedClasses.classListchecked=false;
$scope.getSubscribedClassList = function(classNam) {
if(classNam==="All"){
$scope.selectedClasses.usall=false;
$scope.selectedClasses.classListchecked=false;
}
else{
$scope.selectedClasses.usall=false;
$scope.selectedClasses.sall=false;
$scope.selectedClasses.classListchecked.push(classNam)
}
}
Below is my fiddle link
http://jsfiddle.net/alokranjan39/49cc14yk/38/
I have made few changes in your fiddle (forked it here - http://jsfiddle.net/9Lv8gdr3/1/)
HTML:
<div ng-controller="MyCtrl">
<input type="checkbox" ng-model="masterSelect" ng-click="getSubscribedClassList('All')"> UnSelectAll
<li ng-repeat="class in classList">
<span>
<input type="checkbox" ng-model="class.isSelected" ng-disabled="class.students.length==0">
{{class.name}} </span>
</li>
</div>
JavaScript:
function MyCtrl($scope) {
$scope.classList = [{
isSelected: false,
name: 'Class1'
}, {
isSelected: false,
name: 'Class2'
}, {
isSelected: false,
name: 'Class3'
}, {
isSelected: false,
name: 'Class4'
}];
$scope.getSubscribedClassList = function(classNam) {
if (classNam === "All") {
angular.forEach($scope.classList, function(value, index) {
value.isSelected = $scope.masterSelect;
});
} else {
//you dont ideally need this. get the items with isSelected === true from $scope.classList to get the checked items
}
};
}
To get the list of selected item, just loop through the $scope.classList and get the items for which isSelected === true
Updated your fiddle - http://jsfiddle.net/49cc14yk/43/
HTML :
<div ng-controller="MyCtrl">
<input type="checkbox" ng-model="selectedClasses" ng-click="getSubscribedClassList()">
UnSelectAll
<li ng-repeat="class in classList">
<span>
<input type="checkbox" ng-model="class.value">
{{class.label}}
</span>
</li>
</div>
JS :
function MyCtrl($scope) {
$scope.classList=[{
label: 'Class1', value: false
}, {
label: 'Class2', value: false
}, {
label: 'Class3', value: false
}, {
label: 'Class4', value: false
}];
$scope.getSubscribedClassList = function() {
$scope.classList.forEach(function(obj) {
obj.value = $scope.selectedClasses;
});
}
}
Have updated fiddle for array also - http://jsfiddle.net/49cc14yk/45/
HTML :
<div ng-controller="MyCtrl">
<input type="checkbox" ng-model="selectAll" ng-click="getSubscribedClassList('ALL')">
UnSelectAll
<li ng-repeat="class in classList">
<span>
<input type="checkbox" name="selectedClasses[]" value="{{class}}"
ng-checked="selectedClassList.indexOf(class) > -1" ng-click="getSubscribedClassList(class)">
{{class}}
</span>
</li>
</div>
JS :
function MyCtrl($scope) {
$scope.classList = ['Class1','Class2','Class3','Class4'];
// Initialise below array as per your requirement, maybe blank
$scope.selectedClassList = ['Class1','Class2'];
$scope.getSubscribedClassList = function(value) {
if(value == 'ALL') {
$scope.selectedClassList = [];
if($scope.selectAll) {
$scope.selectedClassList = Object.create($scope.classList);
}
} else {
var idx = $scope.selectedClassList.indexOf(value);
if (idx > -1) {
$scope.selectedClassList.splice(idx, 1);
} else {
$scope.selectedClassList.push(value);
}
}
};
}
Using as object is more appropriate so keeping that answer too

Categories

Resources