0
我想創建一個角樹指令,這裏是代碼:AngularJS指令範圍繼承
//** Tree constructor
var Tree = function() {
return {
restrict: 'EA',
replace: true,
template: "<ul>" +
"<li ng-repeat=\"node in node.children\">" +
"<a ng-click=\"selectNode(node)\" ng-class=\"{selected: isSelected(node)}\">" +
"{{node.name}}" +
"</a>" +
"<tree-children></tree-children>" +
"</li>" +
"</ul>",
scope: {
treeData: '='
},
controller: function($scope) {
//** Selected Node
$scope.selectedNode = null;
//** Node on click
$scope.selectNode = function(node) {
if ($scope.selectedNode !== node) {
$scope.selectedNode = node;
} else {
$scope.selectedNode = null;
}
};
$scope.isSelected = function(node) {
return (node === $scope.selectedNode);
}
},
link: function(scope, elem, attrs) {
//** Watch
scope.$watch('treeData', function(data) {
if (angular.isArray(data)) {
scope.node = {};
scope.node.children = data;
} else {
//***********
}
});
}
}
}
//** Tree children constructor
var TreeChildren = function($compile) {
return {
restrict: 'E',
link: function(scope, elem, attrs) {
var childScope = scope.$new(),
template = '<tree tree-data="node.children"></tree>',
content = $compile(template)(childScope);
//** Append
elem.append(content);
}
};
};
TreeChildren.$inject = ['$compile'];
//** Angular Module
angular
.module('app', [])
.directive('tree', Tree)
.directive('treeChildren', TreeChildren)
.controller('treeCtrl', ['$scope', function($scope) {
$scope.treeData = [
{
name: 'Root',
children: [
{
name: 'Node-1',
children: [
{ name: 'Node-1-1'},
{ name: 'Node-1-2'},
{ name: 'node-1-3'}
]
},
{
name: 'Node-2',
children: [
{ name: 'Node-2-1'}
]
}
]
}
];
}]);
我得建立$scope.selectedNode
成爲全球性問題,現在如果單擊樹節點,css樣式看起來不正確,因爲$scope.selectedNode
僅影響treeChildren
指令中的自己的作用域。
如何從主指令範圍執行範圍繼承?因爲我希望每個節點點擊都會訪問全球$scope.selectedNode
。
我對Understanding Scopes做了一些閱讀,但仍然感到困惑。
希望我解釋清楚,因爲我可憐的英語
感謝您的回覆。這是一箇舊的帖子,我現在使用'as'語法。但我仍然不清楚指令繼承。稍後將更新代碼。 – Neaped 2015-02-02 02:45:55