I have a list of json objects which i want to map to knockout viewmodel list using ko mapping plugin. The below is my code (just to explain my problem, no need to take this code seriously):
var itemsList = [
{ Id: 1, Name: 'A' },
{ Id: 2, Name: 'B' },
{ Id: 3, Name: 'C' }
];
var item = function(data) {
ko.mapping.fromJS(data, {}, this);
}
var listOfItems = ko.observableArray();
var listOfItems = ko.mapping.fromJS(itemsList, {
create: function(options) {
return new item(options.data);
}
});
Now my listOfItems are always empty, why ??
You could really simplify this code and it is become working well.
var itemsList = [{ Id: 1, Name: 'A' }, { Id: 2, Name: 'B' }, { Id: 3, Name: 'C' }];
var viewModel = {
listOfItems: ko.mapping.fromJS(itemsList)
}
ko.applyBindings(viewModel);
Now you have viewModel with observableArray listOfItems, and all items in this array have Id and Name properties.
You can test it with folowing code:
<ul data-bind="foreach: listOfItems">
<li>
<span data-bind="text: Id"></span>
<span data-bind="text: Name"></span>
</li>
</ul>
Related
I am very new to knockout.js (just picked it up yesterday), but I was suggested it for what I'm trying to do.
My dilemma is this:
i set the following "initialData" as a json array:
var initialData = [
{
id: 0,
pcName: "Test1"
},
{
id: 1,
pcName: "Test2"
},
{
id: 2,
pcName: "Test3"
},
{
id: 3,
pcName: "Test4"
},
{
id: 4,
pcName: "Test5"
}
];
followed by the following (simple) model:
var PCModel = function (pcs) {
var self = this;
self.pcsList = ko.observableArray(ko.utils.arrayMap(pcs, function (pc) {
return { id: pc.id, pcName: pc.pcName };
}));
and apply my bindings as such:
ko.applyBindings(new PCModel(initialData));
i then try to loop through my (what should be) pcsList:
<ul class="nav nav-tabs" id="sortable" data-bind="foreach: pcsList">
<li>
<a data-bind="attr: {href: '#' + id}, text: pcName"></a>
</li>
</ul>
And yet, nothing seems to happen. I cant seem to figure out why.
Please help.
For anyone that may stumble around here, my problem was simply not calling applyBindings AFTER the document was ready. wrapping it in $("document").ready(... solved the problem.
Im working on sorting on an array using Angular JS using orderBy. But still its not getting sorted on a particular key.
Here is the code
var app = angular.module('sortModule', [])
app.controller('MainController', function($scope,$filter){
$scope.languages = [
{ name: 'English', image: '/images/english.png',key:2 },
{ name: 'Hindi', image: '/images/hindi.png',key:3 },
{ name: 'English', image: '/images/english.png',key:2},
{ name: 'Telugu', image: '/images/telugu.png',key:1 }];
var newLanguages = []
newLanguages = angular.copy($scope.languages);
function sortImages() {
$scope.languages = []
$scope.keys = []
for(language in newLanguages) {
$scope.keys.push(newLanguages[language])
}
$filter('orderBy')($scope.keys, 'key')
console.log(JSON.stringify($scope.keys))
}
sortImages();
});
Fiddle
Im planning to see sorting based on "key". telugu should come first, english next and hindi last.
you need to have:
$scope.keys = $filter('orderBy')($scope.keys, 'key', false)
the order by filter returns a new array, it does not make changes to the passed array.
updated fiddle:
http://jsfiddle.net/kjuemhua/17/
Remove the OrderBy from the html markup to display unordered list:
<div ng-app="sortModule" class="nav">
<div ng-controller="MainController">
<button ng-click="sort()">Sort
</button>
<div></div>
<div >
<ul>
<li ng-repeat="lang in languages">
<span>{{lang.name}}</span>
</li>
</ul>
</div>
</div>
</div>
Now using the button sort sort the list
var app = angular.module('sortModule', [])
app.controller('MainController', function($scope,$filter){
$scope.languages = [
{ name: 'English', image: '/images/english.png',key:2 },
{ name: 'Hindi', image: '/images/hindi.png',key:3 },
{ name: 'English', image: '/images/english.png',key:2},
{ name: 'Telugu', image: '/images/telugu.png',key:1 }];
var newLanguages = []
newLanguages = angular.copy($scope.languages);
$scope.sort = function(){
$scope.languages = []
$scope.keys = []
for(language in newLanguages) {
$scope.keys.push(newLanguages[language])
}
$scope.keys = $filter('orderBy')($scope.keys, 'key', false);
$scope.languages = $scope.keys;
console.log(JSON.stringify($scope.keys))
}
});
How I Sort a nested Array (2D Array) array from filter of angularjs. It's very Complicated for Me. anybody can help. appreciated for me. thanks...
I have a 2D Array. now how I sort it within ng-repeat.
Template File...
<ul>
<span ng-repeat="list in lists">
<li ng-repeat="list_ in list.list1 | orderBy:'name'">{{list_.name}}</li>
</span>
</ul>
JS file...
$scope.lists = [
{
no : 1,
list1 : [{
name : 'A'
},
{
name : 'M'
}]},
{
no : 2,
list1 : [{
name : 'B'
}]},
{
no : 5,
list1 : [{
name : 'Z'
}]},
{
no : 3,
list1 : [{
name : 'X'
},
{
name : 'T'
}]}
]
plunker here
It could achievable by flatten the array will all the inner object at the same level using custom filter
Markup
<body ng-app="myApp" ng-controller="myCon">
<ul>
<span ng-repeat="list in lists | flatten | orderBy:'+name'">
<li>{{list.name}}</li>
</span>
</ul>
</body>
Filter
app.filter('flatten', function(){
return function(array){
var flattenArray = [];
angular.forEach(array, function(value, index){
angular.forEach(value.list1, function(val, index){
flattenArray.push(val);
})
})
return flattenArray;
}
})
Plunkr Here
to answer your question of how to sort a nested Array array with an angularjs filter, you actually are already doing so. It isn't clear with your data, so I expanded it to make it show what is happening already:
http://plnkr.co/edit/8SjuLc?p=preview
js
var app = angular.module("myApp", []);
app.controller("myCon", myConFun);
myConFun.$inject = ['$scope'];
function myConFun($scope) {
$scope.lists = [{
no: 1,
list1: [{
name: 'Z'
}, {
name: 'X'
}, {
name: 'Y'
}, {
name: 'A'
}, {
name: 'M'
}, {
name: 'C'
}, {
name: 'B'
}]
}, {
no: 2,
list1: [{
name: 'B'
}]
}, {
no: 5,
list1: [{
name: 'Z'
}]
}, {
no: 3,
list1: [{
name: 'X'
}, {
name: 'T'
}]
}
]
}
html
<ul>
<span ng-repeat="list in lists">
<li ng-repeat="sublist in list.list1 | orderBy:'name'">
{{sublist.name}}
</li>
----------
</span>
</ul>
output:
You may need to expand your question further if this isn't the behavior you need
Description
I have a small product order system, where a user can add order lines, and on each order line add one or more products. (I realise it's quite unusual for more than one product to be on the same order line, but that's another issue).
The products that can be selected on each line is based on a hierarchy of products. For example:
Example product display
T-Shirts
V-neck
Round-neck
String vest
JSON data
$scope.products = [
{
id: 1,
name: 'T Shirts',
children: [
{ id: 4, name: 'Round-neck', children: [] },
{ id: 5, name: 'V-neck', children: [] },
{ id: 6, name: 'String vest (exclude)', children: [] }
]
},
{
id: 2,
name: 'Jackets',
children: [
{ id: 7, name: 'Denim jacket', children: [] },
{ id: 8, name: 'Glitter jacket', children: [] }
]
},
{
id: 3,
name: 'Shoes',
children: [
{ id: 9, name: 'Oxfords', children: [] },
{ id: 10, name: 'Brogues', children: [] },
{ id: 11, name: 'Trainers (exclude)', children: []}
]
}
];
T-Shirts isn't selectable, but the 3 child products are.
What I'm trying to achieve
What I'd like to be able to do, is have a 'select all' button which automatically adds the three products to the order line.
A secondary requirement, is that when the 'select all' button is pressed, it excludes certain products based on the ID of the product. I've created an 'exclusion' array for this.
I've set up a Plunker to illustrate the shopping cart, and what I'm trying to do.
So far it can:
Add / remove order lines
Add / remove products
Add a 'check' for all products in a section, excluding any that are in the 'exclusions' array
The problem
However, although it adds the check in the input, it doesn't trigger the ng-change on the input:
<table class="striped table">
<thead>
<tr>
<td class="col-md-3"></td>
<td class="col-md-6"></td>
<td class="col-md-3"><a ng-click="addLine()" class="btn btn-success">+ Add order line</a></td>
</tr>
</thead>
<tbody>
<tr ng-repeat="line in orderHeader.lines">
<td class="col-md-3">
<ul>
<li ng-repeat="product in products" id="line_{{ line.no }}_product_{{ product.id }}">
{{ product.name }} <a ng-click="selectAll(product.id, line.no)" class="btn btn-primary">Select all</a>
<ul>
<li ng-repeat="child in product.children">
<input type="checkbox"
ng-change="sync(bool, child, line)"
ng-model="bool"
data-category="{{child.id}}"
id="check_{{ line.no }}_product_{{ child.id }}"
ng-checked="isChecked(child.id, line)">
{{ child.name }}
</li>
</ul>
</li>
</ul>
</td>
<td class="col-md-6">
<pre style="max-width: 400px">{{ line }}</pre>
</td>
<td class="col-md-3">
<a ng-click="removeLine(line)" class="btn btn-warning">Remove line</a>
</td>
</tr>
</tbody>
</table>
Javascript
$scope.selectAll = function(product_id, line){
target = document.getElementById('line_'+line+'_product_'+product_id);
checkboxes = target.getElementsByTagName('input');
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].type == 'checkbox') {
category = checkboxes[i].dataset.category;
if($scope.excluded.indexOf(parseInt(category)) == -1)
{
checkboxes[i].checked = true;
// TODO: Check the checkbox, and set its bool parameter to TRUE
}
}
}
}
Update with full solution
There were a couple of issues with the above code. Firstly, I was trying to solve the problem by manipulating the DOM which is very much against what Angular tries to achieve.
So the solution was to add a 'checked' property on the products so that I can track if they are contained on the order line, and then the view is updated automatically.
One drawback of this method is that the payload would be significantly larger (unless it is filtered before being sent to the back-end API) as each order line now has data for ALL products, even if they aren't selected.
Also, one point that tripped me up was forgetting that Javascript passes references of objects / arrays, not a new copy.
The solution
Javascript
var myApp = angular.module('myApp', []);
myApp.controller('CartForm', ['$scope', function($scope) {
var inventory = [
{
id: 1,
name: 'T Shirts',
checked: false,
children: [
{ id: 4, name: 'Round-neck', checked: false, children: [] },
{ id: 5, name: 'V-neck', checked: false, children: [] },
{ id: 6, name: 'String vest (exclude)', checked: false, children: [] }
]
},
{
id: 2,
name: 'Jackets',
checked: false,
children: [
{ id: 7, name: 'Denim jacket', checked: false, children: [] },
{ id: 8, name: 'Glitter jacket', checked: false, children: [] }
]
},
{
id: 3,
name: 'Shoes',
checked: false,
children: [
{ id: 9, name: 'Oxfords', checked: false, children: [] },
{ id: 10, name: 'Brogues', checked: false, children: [] },
{ id: 11, name: 'Trainers (exclude)', checked: false, children: []}
]
}
];
$scope.debug_mode = false;
var products = angular.copy(inventory);
$scope.orderHeader = {
order_no: 1,
total: 0,
lines: [
{
no: 1,
products: products,
total: 0,
quantity: 0
}
]
};
$scope.excluded = [6, 11];
$scope.addLine = function() {
var products = angular.copy(inventory);
$scope.orderHeader.lines.push({
no: $scope.orderHeader.lines.length + 1,
products: products,
quantity: 1,
total: 0
});
$scope.loading = false;
}
$scope.removeLine = function(index) {
$scope.orderHeader.lines.splice(index, 1);
}
$scope.selectAll = function(product){
angular.forEach(product.children, function(item){
if($scope.excluded.indexOf(parseInt(item.id)) == -1) {
item.checked=true;
}
});
}
$scope.removeAll = function(product){
angular.forEach(product.children, function(item){
item.checked=false;
});
}
$scope.toggleDebugMode = function(){
$scope.debug_mode = ($scope.debug_mode ? false : true);
}
}]);
Click here to see the Plunker
You are really over complicating things first by not taking advantage of passing objects and arrays into your controller functions and also by using the DOM and not your data models to try to update states
Consider this simplification that adds a checked property to each product via ng-model
<!-- checkboxes -->
<li ng-repeat="child in product.children">
<input ng-model="child.checked" >
</li>
If it's not practical to add properties to the items themselves, you can always keep another array for the checked properties that would have matching indexes with the child arrays. Use $index in ng-repeat for that
And passing whole objects into selectAll()
<a ng-click="selectAll(product,line)">
Which allows in controller to do:
$scope.selectAll = function(product, line){
angular.forEach(product.children, function(item){
item.checked=true;
});
line.products=product.children;
}
With angular you need to always think of manipulating your data models first, and let angular manage the DOM
Strongly suggest reading : "Thinking in AngularJS" if I have a jQuery background?
DEMO
Why ng-change isn't fired when the checkbox is checked programatically?
It happens because
if($scope.excluded.indexOf(parseInt(category)) == -1)
{
checkboxes[i].checked = true;
// TODO: Check the checkbox, and set its bool parameter to TRUE
}
only affects the view (DOM). ng-change works alongside ngModel, which can't be aware that the checkbox really changed visually.
I suggest you to refer to the solution I provided at How can I get angular.js checkboxes with select/unselect all functionality and indeterminate values?, works with any model structure you have (some may call this the Angular way).
I am try to create nested menu using given json data by the client.
Data :
var serverData = [
{
Id: "menuColorSearch",
Text: "Color search"
},
{
Id: "menuAncillaryProductMix",
Text: "Ancillary product mix"
},
{
Id: "menuDocuments",
Text: "Documents"
},
{
Id: "menuColorInfo",
ParentId: "menuDocuments",
Text: "Color info"
},
{
Id: "menuReports",
ParentId: "menuDocuments",
Text: "Reports"
},
{
Id: "menuMaintenance",
Text: "Maintenance"
},
{
Id: "menuPriceManagement",
ParentId: "menuMaintenance",
Text: "Price management"
}
];
I am trying like this :
var Menu = function(dept, all) {
var self = this;
this.id = dept.Id;
this.name = ko.observable(dept.Text);
this.parentId = dept.ParentId;
this.children = ko.observableArray();
ko.utils.arrayForEach(all || [], function(menu) {
if(menu.ParentId){
if (menu.ParentId === self.id) {
self.children.push(new Menu(menu, all));
}
}else{
new Menu(menu, all)
}
});
};
var ViewModel = function(data) {
this.root = new Menu(data[0], data);
};
$(function() {
ko.applyBindings(new ViewModel(serverData));
});
Templates :
<div data-bind="with: root">
<ul data-bind="template: 'deptTmpl'">
</ul>
</div>
<script id="deptTmpl" type="text/html">
<li>
<a data-bind="text: name"></a>
<ul data-bind="template: { name: 'deptTmpl', foreach: children }">
</ul>
</li>
</script>
problem is that its only work when 2nd and 3rd object has parent ID. i am trying something like it should make nested menu according to given json data. so id there is no parent id on object it should add on root. and if object has parent id it should add according to parent id.
Please help me to correct my code or guide me if these is another way to do this in KnockoutJS.
Thanks
This should help you http://jsfiddle.net/MCNK8/3/, the main idea is to rebuild main data array, by placing child inside parent
HTML
<script id="nodeTempl" type="text/html">
<li>
<a data-bind="text: Text"></a>
<ul data-bind="template: {name: nodeTemplate, foreach: children }"></ul>
</li>
</script>
<script id="nodeLeafTempl" type="text/html">
<li>
<a data-bind="text: Text"></a>
</li>
</script>
<ul data-bind="template: {name: nodeTemplate, foreach: children }"></ul>
Javascript (#see fiddle)
var serverData = [
{
Id: "menuColorSearch",
Text: "Color search"
},
{
Id: "menuAncillaryProductMix",
ParentId: 'menuColorSearch',
Text: "Ancillary product mix"
},
{
Id: "menuDocuments",
Text: "Documents"
},
{
Id: "menuColorInfo",
ParentId: "menuReports",
Text: "Color info"
},
{
Id: "menuReports",
ParentId: "menuDocuments",
Text: "Reports"
},
{
Id: "menuMaintenance",
ParentId: 'menuReports',
Text: "Maintenance"
},
{
Id: "menuPriceManagement",
ParentId: "menuMaintenance",
Text: "Price management"
}
];
function getNestedMenu(index, all) {
var root = all[index];
if(!root){
return all;
}
if(!all[index].children){
all[index].children = [];
}
for(var i = 0; i < all.length; i++){
//<infinity nesting?>
//put children inside it's parent
if(all[index].Id == all[i].ParentId){
all[index].children.push(all[i]);
all[i].used = true;
}
//this is needed for each item, to determine which template to use
all[index].nodeTemplate = function(node) {
return node.children.length > 0 ? 'nodeTempl' : 'nodeLeafTempl';
}
//</infinity nesting?>
}
return getNestedMenu(++index, all);
};
function getModel(data) {
var items = getNestedMenu(0, data);
//<remove duplicates, for infinity nesting only>
for(var i = 0; i < items.length; i++){
if(items[i].used){
items.splice(i, 1);
i--;
}
}
//</remove duplicates, for infinity nesting only>
//<build root item>
var model = {};
model.children = ko.observableArray(items);
model.nodeTemplate = function(node) {
return node.children.length > 0 ? 'nodeTempl' : 'nodeLeafTempl';
}
//</build root item>
console.log(items);
return model;
};
(function() {
//new ViewModel(serverData);
ko.applyBindings(getModel(serverData));
})();