AngularJS:树指令不能正常工作

时间:2014-06-05 22:30:37

标签: angularjs angularjs-directive angularjs-scope angularjs-ng-repeat

创建一个带有隔离范围的角度树指令,该范围绑定两个属性的值... items和item-click-handler。这是代码:

HTML

<div ng-app="myapp">
<div ng-controller="TreeCtrl">
    <item-tree class="tree" items="treeFamily" item-click-handler="groupSelectedFunction(itemId)"></item-tree>
</div>

JAVASCRIPT

var module = angular.module('myapp', []);

module.controller("TreeCtrl", function($scope) {
    $scope.treeFamily = [{
        Name : "Parent",
        Code : "Parent",
        Children: [{
            Name : "Child1",
            Code : "Child1",
            Children: [{
                Name : "Grandchild1",
                Code : "Grandchild1",
                Children: []
            },{
                Name : "Grandchild2",
                Code : "Grandchild2",
                Children: []
            },{
                Name : "Grandchild3",
                Code : "Grandchild3",
                Children: []
            }]
        }, {
            Name: "Child2",
            Code : "Child2",
            Children: []
        }]
    }];
    $scope.groupSelectedFunction = function (itemId) {
                alert(itemId + ' selected');
    }
});

module.directive("itemTree", function($compile) {
    return {
        restrict: "E",
        scope: {
            items: '=',
            itemClickHandler: '&'
        },
        template: 
            '<ul id="group-nodes" ng-repeat="item in items">' +                
                '<li id={{ item.Code }}>' + 
                    '<a ng-click="itemClickHandler({itemId: 1})">{{ item.Name }}</a>'+
                    '<item-tree items="item.Children" item-click-handler="itemClickHandler(itemId)"></item-tree>' +
                '</li>' +
            '</ul>',
        compile: function(tElement, tAttr) {
            var contents = tElement.contents().remove();
            var compiledContents;
            return function(scope, iElement, iAttr) {
                if(!compiledContents) {
                    compiledContents = $compile(contents);
                }
                compiledContents(scope, function(clone, scope) {
                         iElement.append(clone); 
                });
            };
        }
    };
});

树很好。如果我单击顶级父节点,控制器功能将运行并显示具有预期值的警报:&#34;父选择&#34; 。但是,如果单击任何其他节点,则该功能会运行,但警告消息为:&#34;未定义选择&#34; 。对Angular来说比较新,所以这个让我挠头。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

目前尚不清楚每个子节点的警报中应显示哪些ID,但更明显的是您为什么会看到undefined而不是值...

使用&隔离范围类型时,从模板传递给函数的参数需要在一个对象中传递,后面是顶级元素:

ng-click="itemClickHandler({itemId: 1})"

您需要为孩子遵循相同的语法。所以,

item-click-handler="itemClickHandler(itemId)"

应该是

item-click-handler="itemClickHandler({itemId: itemId})"

Demo