dacox
dacox

Reputation: 502

Pass function from controller scope to directive isolate scope

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>

Upvotes: 0

Views: 2668

Answers (2)

ArslanW
ArslanW

Reputation: 353

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.

Upvotes: 0

Jesse Buitenhuis
Jesse Buitenhuis

Reputation: 670

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});
  };
});

Upvotes: 2

Related Questions