I'm trying to use a global function defined in a parent constructor within the directives on the page which will be called recursively. However not able to figure out how to pass it through all the layers cleanly. using the $parent I can pass it through one layer only.. What would be the best way to achieve this?
<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);
});
};
}
};
});