3

我正在尝试在页面上的指令中使用父构造函数中定义的全局函数,该指令将被递归调用。但是无法弄清楚如何干净地通过所有层。使用 $parent 我只能通过一层.. 实现这一目标的最佳方法是什么?

http://jsfiddle.net/J8tFS/

<div ng-app="myapp">
<div ng-controller="TreeCtrl">
    <tree family="treeFamily"></tree>
</div>

module.controller("TreeCtrl", function($scope) {
$scope.treeFamily = {
    name : "Parent",
    children: [{
        name : "Child1",
        children: [{
            name : "Grandchild1",
            children: []
        },{
            name : "Grandchild2",
            children: []
        },{
            name : "Grandchild3",
            children: []
        }]
    }, {
        name: "Child2",
        children: []
    }]
};
$scope.toUpper = function(strInput) {
     return strInput.toUpperCase();   
}
});

module.directive("tree", function($compile) {
return {
    restrict: "E",
    scope: {family: '='},
    template: 
        '<p>{{ family.name }}</p>'+
        '<p>{{ $parent.toUpper(family.name) }}</p>' +
        '<ul>' + 
            '<li ng-repeat="child in family.children">' + 
                '<tree family="child"></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); 
            });
        };
    }
};

});

4

1 回答 1

1

你真的需要使用隔离范围吗?如果不是,请不要使用它并访问父范围内的所有内容。

module.directive("tree", function($compile) {
return {
    restrict: "E",
    template: 
        '<p>{{ family.name }}</p>'+
        '<p>{{ $parent.toUpper($parent.family.name) }}</p>' +
        '<ul>' + 
            '<li ng-repeat="child in family.children">' + 
                '<tree family="child"></tree>' +
            '</li>' +
        '</ul>',
    compile: function(tElement, tAttr) {
        var contents = tElement.contents().remove();
        var compiledContents;
        return function(scope, iElement, iAttr) {
            scope.family = scope.$eval(iAttr.family);

            if(!compiledContents) {
                compiledContents = $compile(contents);
            }
            compiledContents(scope, function(clone, scope) {
                     iElement.append(clone); 
            });
        };
    }
};
});

这是固定的小提琴:http: //jsfiddle.net/J8tFS/1/

于 2013-05-29T22:09:15.487 回答