我想用anugularJS生成一个n级的层次无序列表,并已能够成功地这样做。但现在,我在指令和控制器之间存在范围问题。我需要在指令模板中通过ng-click调用的函数内更改父级的范围属性。如何正确地绑定指令和控制器之间的角度与angularJS
见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),但这种更改只发生在本地。当我点击一个项目时,预期的行为是“Selected:None”应该改为“Selected:xxx”,其中xxx是被点击的项目。
我没有适当地绑定父范围和指令之间的属性?我如何将属性更改传递给父范围?
希望这是明确的。
在此先感谢您的帮助。
欢迎来到StackOverflow!如果您在接近尾声的时候以实际问题的形式来重述它,它可能会改进您的帖子。 – 2013-03-13 15:20:51