I am working with a data structure that is nested infinitely. There is a top-level object containing a collection of objects, and each of these objects can also have their own collection of objects.
To iterate through this tree, I have implemented the following code:
collection.js
app.directive('collection', function() {
return {
restrict: 'E',
replace: true,
scope: {
collection: '='
},
templateUrl: 'collection.html'
};
});
collection.html
<ul>
<member ng-repeat="member in collection" member="member"></member>
</ul>
member.js
app.directive('member', function($compile) {
return {
restrict: 'E',
replace: true,
scope: {
member: '='
},
templateUrl: 'member.html',
link: function(scope, element, attrs) {
var collection = '<collection collection="member.children"></collection>';
if (scope.member.children) {
$compile(collection)(scope, function(cloned, scope) {
element.append(cloned);
});
}
}
};
});
member.html
<li>
{{ member }}
</li>
index.html
<div data-ng-controller="collectionController">
<collection collection="collection"></collection>
</div>
I am trying to enable clicking on a member at any level of nesting and setting the controller's selectedMember property as that member.
This is what I've attempted:
app.controller('collectionController', function($scope, collection) {
collection.getCollection().then(function(collection) {
$scope.collection = collection;
});
$scope.selectMember = function(member) {
$scope.selectedMember = member;
};
});
Since I need to call a function defined in the parent scope (the controller), I believe I need to pass down the selectMember function in the following way:
index.html
...
<collection collection="collection" select-member="selectMember"></collection>
...
collection.html
<member ng-repeat="member in collection" member="member"
select-member="selectMember()" ng-click="selectMember(member)">
</member>
collection.js
...
scope: {
collection: '=',
selectMember: '&selectMember'
}
...
member.js
...
scope: {
member: '=',
selectMember: '='
}
...
However, I'm facing issues getting the function to trigger correctly and set the controller scope's selectedMember property. The parameter passed to the selectMember function is undefined.
It seems like there might be a misunderstanding regarding scopes, complicated by the nested nature of the problem at hand.
Any suggestions or ideas would be greatly appreciated.
Edit: Here's a plunker: http://plnkr.co/edit/JfxpoLLgpADs9RXSMife