我有一个构建 TreeView 的指令。它基于http://jsfiddle.net/KNM4q/113/处的代码示例。我希望能够单击树中的任何节点,并让单击在 Controller 中执行处理特定于该节点的数据的方法。虽然我已经让代码在根节点和子节点中工作,但我无法使其与孙子或伟大的孙子节点一起工作。
这是骗子:
http://plnkr.co/edit/AKiD8ZyKK8dUSPEcWI3p?p=preview 。
这是 HTML:
<div ng-controller="appCtrl">
<tree val="treeData" zo="itemDetail(param)" ></tree>
</div>
这是指令:
angular.module('components')
.directive('tree', function ($compile) {
return {
restrict: 'E',
terminal: true,
scope: { val: '=', parentData:'=', zo:'&' },
link: function (scope, element, attrs) {
var template = '<span>{{val.text}}</span><button ng-click="showDetail()" ng-show="val.text">Show Detail</button> ';
if (angular.isArray(scope.val.items)) {
template += '<ul class="indent"><li ng-repeat="item in val.items"><tree val="item" parent-data="val.items" zo=zo({param:item.text}) > </tree></li></ul>';
}
scope.showDetail = function(index) {
var param = 'aaa';
scope.zo();
};
var newElement = angular.element(template);
$compile(newElement)(scope);
element.replaceWith(newElement);
}
}
});
这是 Controller :
function appCtrl($scope) {
var treeData = {
"text": "root",
"items": [{
"text": "Furniture",
"items": [{
"text": "Tables & Chairs"
}, {
"text": "Sofas",
"items": [{
"text": "Tables & Chairs"
}, {
"text": "Sofas"
}]
}, {
"text": "Occasional Furniture"
}]
}, {
"text": "Decor",
"items": [{
"text": "Bed Linen"
}, {
"text": "Curtains & Blinds"
}, {
"text": "Carpets"
}]
}]
};
//initial parameter that is sent
$scope.param = 'root';
$scope.treeData = treeData;
$scope.itemDetail = function (param){
alert('in controller ' + param);
}
}
最佳答案
您希望将函数作为对象引用传递,并在指令范围内使用 =
而不是 &
两种方式将其绑定(bind)回每个父级别。
HTML
<!-- notice removed "()" -->
<tree val="treeData" zo="itemDetail" ></tree>
JS
由于 zo
绑定(bind)到父作用域函数,因此可以在模板 html 中使用它
.directive('tree', function ($compile) {
return {
restrict: 'E',
terminal: true,
scope: { val: '=', parentData:'=', zo:'=' },
link: function (scope, element, attrs) {
var template = '<span>{{val.text}}</span><button ng-click="zo(val.text)" ng-show="val.text">Show Detail</button> ';
if (angular.isArray(scope.val.items)) {
template += '<ul class="indent"><li ng-repeat="item in val.items"><tree val="item" parent-data="val.items" zo="zo" > </tree></li></ul>';
}
var newElement = angular.element(template);
$compile(newElement)(scope);
element.replaceWith(newElement);
}
}
简单来说,这与执行以下操作相同:
function foo( param ){
alert(param);
}
var bar = foo;
bar('someString') // alerts "someString"
关于javascript - Angular 指令 - 无法访问 TreeView 中的子节点或孙节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24965922/