Angular Material Tree view
Checkbox
在我第一次尝试折叠/展开时工作正常,checked
是Parent Node
还是Child Node
,但它是我第二次尝试Checked
不同的node
(即Child Node
)时无法正常工作。我使用custom指令来实现Tree View
功能。以下是我的代码。
自定义指令
NFSModule.directive('nfsTree', function () {
return {
restrict: 'E',
replace: true,
scope: {
tree: '=source',
},
template: '<nfs-node ng-repeat="c in tree.children" cnode="c"></nfs-node>'
};
});
NFSModule.directive('nfsNode', function ($compile) {
return {
restrict: 'E',
replace: true,
scope:{
node: '=cnode'
},
template: '<li><span ng-click="toggleVisibility(node)"> {{ ( node.childrenVisibility && node.children.length ) ? "+" : "-" }}</span>' +
'<nfs-tree-checkbox ng-model="node.checked" ng-click="checkNode(node)"><span ng-bind="node.name"></span></nfs-tree-checkbox></li>', // HTML for a single node.
link: function (scope, element) {
/*
* Here we are checking that if current node has children then compiling/rendering children.
* */
if (scope.node && scope.node.children && scope.node.children.length > 0) {
scope.node.childrenVisibility = true;
var childNode = $compile('<ul ng-if="!node.childrenVisibility"><nfs-tree source="node" ></nfs-tree></ul>')(scope);
element.append(childNode);
} else {
scope.node.childrenVisibility = false;
}
},
controller: ["$scope", function ($scope) {
// This function is for just toggle the visibility of children
$scope.toggleVisibility = function (node) {
if (node.children) {
node.childrenVisibility = !node.childrenVisibility;
}
};
// Here We are marking check/un-check all the nodes.
$scope.checkNode = function (selectednode) {
if (selectednode.checked != undefined) {
var has_child = angular.isArray(selectednode.children);
if (has_child = true)
{
checkChildren(selectednode);
}
}
function checkChildren(c) {
angular.forEach(c.children, function (c) {
c.checked = selectednode.checked;
});
}
};
}]
};
});
NFSModule.directive('nfsTreeCheckbox', function () {
return {
restrict: 'E',
replace: true,
transclude: true,
scope: {
name: '@',
ngModel: '=',
ngClick: '=',
ngDisabled: '=',
label: '@'
},
template: function (elem, attr) {
return '<md-input-container class="md-inline" style="height:10px !important; margin-top:-5px; !important; margin-left:5px !important;">' +
'<md-checkbox ng-model="ngModel" ng-click="ngClick" ng-disabled="ngDisabled" aria-label="{{label}}" class="md-primary">' +
'<ng-transclude></ng-transclude>' +
' </md-checkbox>' +
'</md-input-container>'
}
};
});
$ SCOPE
$scope.location = {
children:
[
{
name: 'Europe',
children: [
{
name: 'Italy',
children: [
{
name: 'Rome'
},
{ name: 'Milan' }
]
},
{ name: 'Spain' }
]
},
{
name: 'South America',
children: [
{ name: 'Brasil' },
{ name: 'Peru' }
]
}
]
};
HTML
<ul >
<nfs-tree source="location"></nfs-tree>
</ul>