我正在尝试使用 anugularJS 生成一个 n 级分层无序列表,并且已经能够成功地做到这一点。但是现在,我在指令和控制器之间遇到了范围问题。我需要在指令模板中通过 ng-click 调用的函数中更改父级的范围属性。
请参阅http://jsfiddle.net/ahonaker/ADukg/2046/ - 这是 JS
var app = angular.module('myApp', []);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
$scope.itemselected = "None";
$scope.organizations = {
"_id": "SEC Power Generation",
"Entity": "OPUNITS",
"EntityIDAttribute": "OPUNIT_SEQ_ID",
"EntityID": 2,
"descendants": ["Eastern Conf Business Unit", "Western Conf Business Unit", "Atlanta", "Sewanee"],
children: [{
"_id": "Eastern Conf Business Unit",
"Entity": "",
"EntityIDAttribute": "",
"EntityID": null,
"parent": "SEC Power Generation",
"descendants": ["Lexington", "Columbia", "Knoxville", "Nashville"],
children: [{
"_id": "Lexington",
"Entity": "OPUNITS",
"EntityIDAttribute": "OPUNIT_SEQ_ID",
"EntityID": 10,
"parent": "Eastern Conf Business Unit"
}, {
"_id": "Columbia",
"Entity": "OPUNITS",
"EntityIDAttribute": "OPUNIT_SEQ_ID",
"EntityID": 12,
"parent": "Eastern Conf Business Unit"
}, {
"_id": "Knoxville",
"Entity": "OPUNITS",
"EntityIDAttribute": "OPUNIT_SEQ_ID",
"EntityID": 14,
"parent": "Eastern Conf Business Unit"
}, {
"_id": "Nashville",
"Entity": "OPUNITS",
"EntityIDAttribute": "OPUNIT_SEQ_ID",
"EntityID": 4,
"parent": "Eastern Conf Business Unit"
}]
}]
};
$scope.itemSelect = function (ID) {
$scope.itemselected = ID;
}
}
app.directive('navtree', function () {
return {
template: '<ul><navtree-node ng-repeat="item in items" item="item" itemselected="itemselected"></navtree-node></ul>',
restrict: 'E',
replace: true,
scope: {
items: '='
}
};
});
app.directive('navtreeNode', function ($compile) {
return {
restrict: 'E',
template: '<li><a ng-click="itemSelect(item._id)">{{item._id}} - {{itemselected}}</a></li>',
scope: {
item: "=",
itemselected: '='
},
controller: 'MyCtrl',
link: function (scope, elm, attrs) {
if ((angular.isDefined(scope.item.children)) && (scope.item.children.length > 0)) {
var children = $compile('<navtree items="item.children"></navtree>')(scope);
elm.append(children);
}
}
};
});
这是HTML
<div ng-controller="MyCtrl">
Selected: {{itemselected}}
<navtree items="organizations.children"></navtree>
</div>
请注意,该列表是从模型生成的。而ng-click调用该函数设置父作用域属性(itemselected),但改变只发生在本地。当我单击一个项目时,预期的行为是“已选择:无”应更改为“已选择:xxx”,其中 xxx 是单击的项目。
我是否没有适当地绑定父范围和指令之间的属性?如何将属性更改传递给父范围?
希望这很清楚。
提前感谢您的帮助。