I'm trying to pass a callback function from a controller to a directive.
Here's the callback function code:
$scope.onImageSelect = function(image) {
alert('SET');
$scope.card.image = image;
};
Directive usage:
<google-image-search callback="onImageSelect" />
Directive code:
ngmod.directive('directive', function() {
return {
templateUrl: '/templates/template.html',
scope: {
callback: '&'
}
}
});
Callback usage in template:
<a data-ng-click="callback(url)"></a>
However, this gives me the following error:
TypeError: Cannot use 'in' operator to search for 'onImageSelect'
I've seen a lot of similar questions, but could not understand where am I wrong.
Following code is tested and working..
Sample Directive code
Sample Controller
Many AngularJs developers have already know about AngularJs Directives and probably know about directive scope and it's methods.
As you know, there are 3 AngularJs Directive scope methods: '@', '=', '&', but now we are going to talk about only '&' method.We are going to see, how we can implement method '&' in our applications.
When we define any function inside current scope and want to implement it to any directives,Remember one thing: you have to pay attention on your function's arguments and their order.If you want more here is a great article about it:
http://www.w3docs.com/snippets/angularjs/angularjs-directive-scope-method.html
While calling the expression method from the directive you need to pass the parameter from the directive in
JSON
format, also you should correct your directivecallback
attribute value to pass function likecallback="onImageSelect(image)"
Directive usage:
Directive Template
try to change the scope object to be like this
and it will work
Simply use:
This example from AngularJS developer guide is pretty similar to your case: http://plnkr.co/edit/hYBxk070sgw54RElyWNq?p=preview