Angular: Empty Fiddle
http://angularjs.org/
by Randy Crews
HTML
<script src="http://code.angularjs.org/angular-1.0.0rc8.js"></script>
<script type="text/ng-template" id="tree_item_renderer.html">
<input type="checkbox" ng-model="data.chk" ng-change="setData(data)"> {{ data.text }}
<ul>
<li ng-repeat = "data in data.children" ng-include= "'tree_item_renderer.html'"></li>
</ul>
</script>
<ul ng-app="Application" ng-controller="TreeController">
<li ng-repeat="data in tree" ng-include="'tree_item_renderer.html'"></li>
<button ng-click="submit()">Submit</button>
<div>{{results}}</div>
</ul>
CSS
ul {
list-style: circle;
}
li {
margin-left: 20px;
}
JavaScript
angular.module("myApp", [])
.controller("TreeController", ['$scope', function ($scope) {
$scope.nodeSearch = function (treeNodes, searchID) {
for (var nodeIdx = 0; nodeIdx <= treeNodes.length - 1; nodeIdx++) {
var currentNode = treeNodes[nodeIdx];
if (currentNode.id == searchID) {
return currentNode;
} else {
var foundDescendant = $scope.nodeSearch(currentNode.children, searchID);
if (foundDescendant) {
return foundDescendant;
}
}
}
return false;
};
$scope.setData = function (data) {
var elements = [];
if (data.chk === true && data.parentId !== null) {
elements.push($scope.nodeSearch($scope.tree, data.parentId));
} else if (data.chk === false) {
angular.forEach(data.children, function (child, key) {
elements.push($scope.nodeSearch(data.children, child.id));
});
}
angular.forEach(elements, function (element, key) {
element.chk = data.chk;
$scope.setData(element);
});
};
$scope.chk = [];
$scope.tree = [{
"id": "1",
"text": "Women",
"parentId": null,
"children": [{
"id": "4",
"text": "Jeans",
"parentId": "1",
"chk": true,
"children": [{
"id": "5",
"text": "Levi's",
"parentId": "4",
"children": []
}]
}]
}, {
"id": "2",
"text": "Men",
"parentId": null,
"children": [{
"id": "7",
"text": "Sweatshirts",
"parentId": "2",
"children": []
}, {
"id": "9",
"text": "T-shirts",
"chk": true,
...