Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: Call external functions from directive?

I'm trying to create a custom component that uses external functions defined in the controller, but I'm experiencing different problems.

Example:

I want to create a custom input with a external function defined in the controller, like:

<custom-input type="text" ext-function="checkLength(this)"></custom-input>
<custom-input type="password" ext-function="checkPasswordIsStrong(this)"></custom-input>

The thing is that I've tried different approaches to call this from the directive but with no success at all, like:

Directive:

 link: function(scope, element, attrs, ctrl) {
    if (typeof(attrs.extFunction) != "undefined") {
       scope.$eval(attrs.extFunction);
    }
 }

Controller

$scope.checkLength = function(element){
   console.log('Checking length from: '+element);
}

$scope.checkPasswordIsStrong = function(element){
   console.log('Checking password from: '+element);
}
  1. How should I call from inside the directive these dynamic external functions?
  2. How could I pass the element to the function from the html? I used "this", but it doesn't work at all.

EDITED

I finally figured it out.

Solution: http://plnkr.co/edit/6A9DsCruV7yTQmTRU65j?p=preview

like image 261
DreaMTT Avatar asked Jan 20 '26 06:01

DreaMTT


1 Answers

For example, you can use the & binding, like:

scope: {
    'fctn': '&extFunction'
},

That way it is part of the directive's scope. See: http://docs.angularjs.org/guide/directive

like image 124
Moritz Petersen Avatar answered Jan 22 '26 21:01

Moritz Petersen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!