0

I am using AngularJS and am trying to pass a function on my controller's scope to a directive's isolate scope.

I know I have done this before, but am having issues this time.

The function takes two inputs, and logs them to the console.

However, when I pass it to my directive as

<div my-dir my-function="functionName"></div>

or

<div my-dir my-function="functionName()"></div>

And attempt to call it from my directives controller, I actually get a function that takes no arguments and returns my function.

that is, instead of calling

ctrl.functionName(a,b)

I have to call

ctrl.functionName()(a,b)

Any help would be greatly appreciated.

I have seen some reference to syntax like this:

 <div my-dir my-function="functionName({})"></div>
2

2 Answers 2

2

html:

<div my-dir my-function="functionName()"></div>

directive:

angular.directive('myDir', function() {
  return {
    scope: {
      callback: '&myFunction'
    },
    controller: function($scope) {
      $scope.callback({param1: val1, param2: val2});
  };
});
Sign up to request clarification or add additional context in comments.

1 Comment

Using this notation with the parameter dictionary worked. Why is this necessary? Also, I had to pass in the method to the directive with the argument names
0

Try the following code with scope isolation:

angular.module("Demo", [])  
  .controller("ChildCtrl", function($rootScope, $scope) {
    $scope.testFunc = function (a, b) {
        return a + b;
    }
 })
.directive("isoElement", function() {
  return {
    restrict: "E",
    scope: {
        testFunc: '&'
    },
    link: function(scope) {
      console.log(scope.testFunc()(1, 2));
    }
  };
}); 

Directive usage will be:

<div ng-app="Demo" ng-controller="ChildCtrl">
    <iso-element test-func="testFunc"></iso-element>
</div>

You will need to do scope.testFunc()(..) because scope.testFunc() will return the function itself. IMO this is more understandable than approaching the problem from another side.

2 Comments

My problem was I didn't understand why I had to call testFunc()(), when testFunc is a function that returns a value, not a function. The correct answer seems to be calling the function from within the directive this notation testFunc({arg1:1,arg2:2})
In that case, "&" passes only the reference and using "=" passes the whole function. When the reference is passed then we need to first get the function itself and then invoke it. On the othe rhand if we use "=" in scope isolation then we get the function itself in the scope and can simply call it.

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.