I am trying to call a function from a directive and pass a parameter. The callback function is being passed in to the isolate scope. I have two problems. First, this doesn't work at all when nested inside an ng-repeat and second, even when not in ng-repeat it I don't know how to pass a parameter to the callback function. Here is a plunker showing the problem: http://plnkr.co/edit/3FN0o3UE99wsmUpxMe4x?p=preview
Notice that when you click on "This works", it at least executes the function from the parent scope, but when clicking on the others, it does nothing (because they're inside an ng-repeat). That's the first problem.
The second problem is that when you click on "This works", even though it successfully calls the function, I can't figure out how to pass along the user from the directive scope (notice that it alerts undefined).
Here is a sample directive (much simplified from my real-world application):
var app = angular.module('plunker', []);
app.controller("AppCtrl", function($scope) {
$scope.click = function(user) {
alert(user)
}
$scope.users = [{
name: 'John',
id: 1
}, {
name: 'anonymous'
}];
});
app.directive("myDir", function($compile) {
return {
scope: {
user: '=',
click: '&'
},
compile: function(el) {
el.removeAttr('my-dir');
el.attr('ng-click', 'click(user)')
var fn = $compile(el);
return function(scope, el){
fn(scope);
};
}
};
});
Here is the html:
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="[email protected]" src="http://code.angularjs.org/1.2.12/angular.js" data-semver="1.2.12"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="AppCtrl">
<a my-dir user="{name: 'Works', id: 0}" click="click()">This works</a>
<a my-dir user="user" click="click()" ng-repeat="user in users"><br>{{user.name}}</a>
</div>
</body>
</html>
Thanks!