1

I have a function I want to pass to a directive. The directive is used in two places, however, and at the first place the function takes two parameters, the second place it only takes one parameter:

Function1(param1)

Function2(param1, param2)  

I only have access to param1 in the directive. How do I modify Function2 so that it returns Function1? I have thought about changing the implementation of Function2 to the following:

Function2(param2) { 
 return function(param1) {
    //do something with param2
 }

}

And passing it to the directive like this:

 function="Function2(param2)"

However, this causes the Angular digest cycle to go into an infinite loop. How can I resolve this issue?

2 Answers 2

1

First of all, i wouldn't use function as an attribute name, since it's a reserved word. You can add another attribute on the scope like: function-params="[param1, param2]"

so the element will look like this:

<my-directive func="myFunction" function-params="[param1, param2]"></my-directive>

Then, in the directive you'll call it using apply:

angular.module('app').directive('myDirective', {
  ...
  scope: {
     func: '=',
     functionParams: '='
  },
  link: function(scope){
      scope.func.apply(null, scope.functionParams);
  }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that's a lot more clean.
0

I solved this issue by using a workaround where I pass param2 into the directive scope, along with a boolean indicating whether the function passed into the directive is Function1 or Function2. If Function1, call the passed in function, let's call it passed_in_function, like this:

  passed_in_function(param1)

If Function 2, call it like this:

 passed_in_function(param1, param2)

Ugly, but works. I'm sure someone can provide a better solution though.

Comments

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.