Reputation: 95
I have a custom AngularJS directive, which is rendering a ng-repeat. In this ng-repeat I want to pass one element to a function. The function is called, but item is undefined.
Important: I get my persons form a rest-call.
//Inside the template
<ul class="list-group" data-ng-repeat="person in persons track by $index">
<li>
... ng-click=fn(person) ...
</li>
</ul>
This is the function I like to pass the person.
//in outside controller
$scope.showPerson = function (item) {
console.log(item) // this is undefined
}
My directive looks like this:
directive('custom', function () {
return {
restrict: 'E',
scope: {
persons: "=persons",
fn: "&"
},
templateUrl: "/views/templates/persons.html"
};
});
I call my directive like this:
<custom persons="persons" fn="showPerson()"></custom>
Any ideas why item is undefined? The only thing I can imagine is a timing issue, because the directive fires before the array of persons is filled (from the rest call).
Upvotes: 4
Views: 1947
Reputation: 40298
Functions passed to isolated scope have a peculiarity, when accepting arguments. For starters, define the argument in the HTML:
<custom persons="persons" fn="showPerson(x)"></custom>
Note the argument name: x
. Now from within the template of the directive (this is the peculiarity):
<button ng-click="fn({x: person})" ...>
Where x
is the name of the argument defined above.
Upvotes: 3