How To Pass A Function Handler From Controller Into Directive Isolated Scope In Angularjs?
Solution 1:
you can do something like
angular.module('app').directive('custom', function(){
return {
restrict: 'A',
scope: {
text: '@',
click: '=click'
},
link: function(scope, element){
// console.dir(scope.click);
element.bind("click",function(){
scope.click('Hello, Plunker!');
});
element.text('Hello, Plunker!');
}
}
})
here you get click function from parent scope by click: '=click'
and bind that function to click on the element.
here is plnkr http://plnkr.co/edit/Ekw8I6Kg6tDOnIrnv4za?p=preview
or you can just pass the parameter into your directive like this http://plnkr.co/edit/mBbZil1jc4El2Jk79ru7?p=preview
Solution 2:
By using click: '&click'
(which can be shortened to just click: '&'
), you're saying "make click
on the inner scope execute the expression in 'click'
attribute". That means that you need to actually call the method in the expression, not just point to it.
<h1click="ctrl.click()">...</h1>
If, on the other hand you want to get a reference to the outer function and then play with it (e.g. pass arguments to it), you need to get it using:
scope: {
click: '='
}
or just use solution by @michael-zuchetta, which was new to me :)
Solution 3:
This is a solution:
<h1customtext="Hello Plunker!"click="click(message)"></h1>
Add the message parameter and then bind it :
scope.click({message: "Hello Plunker:"});
This is the working example: http://jsfiddle.net/u748hLvn/2/
Post a Comment for "How To Pass A Function Handler From Controller Into Directive Isolated Scope In Angularjs?"