Calling function from your angularjs directive
Calling function from your angularjs directive
Calling function from your angularjs directive is super easy. To call a function from your directive you need to get the expression from your custom attribute and then by using $parser service we can parser the given expression and can call that parsed expression very easily.
Here is the code for directive that using isolated scope.
var module = angularjs.module('myApp',[]);
module.directive('myCustomFunction',['$parse', function($parse) {
return {
scope : false, // no isolated scope
replace : false,
link:function(scope, element, attr) {
element.click = function() {
// Calling function parsing the expression first and then
// executing the expression under directive scope here
// directive scope is parent controller scope
$parse(attr.myCustomFunction)(scope);
};
};
}]);
If you are using isolated scope you can do the same by using function binding to the scope variable. Here is the example.
module.directive('myCustomFunction',['$parse', function($parse){
return {
scope : {
// Isolated scope binding a function to scope variable
myCustomFunction : '&'
},
replace : false,
link : function(scope, element, attr) {
element.click = function() {
// Calling bind function
scope.myCustomFunction();
};
};
}]);
Html code (View code)
<button my-custom-function="someControllermethod()">My Custom Directive example</button>
Thats all. Thanks.

0 comments: