3

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

1

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

That works perfectly. Thanks Moritz! I'm now trying to solve the second question: How could I pass the element to the function from the html? Check the example here: plnkr.co/edit/6A9DsCruV7yTQmTRU65j?p=preview

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.