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