farolfo
farolfo

Reputation: 388

Function with args in parent scope is being binded but not being called in angular directive

I'm trying to call a function that is in the parent scope of a directive but it is not being called. We want to pass the parameter 'arg' that is being modified to the parent scope and do some logic to it like 'arg = arg + 1', but this function is not being called.

   function MyCtrl($scope) {
        $scope.arg = 0

        $scope.myFunction = function(arg) {

           //do some logic like '+ 1'
           arg++;

           $scope.arg = arg;
        }
    }

    myApp.directive('directive', function () {

    return {
        restrict: 'E',
        scope: {
            arg: '=arg',
            fun: '&'
        },

        template: '<input ng-model="arg"/>',

        link: function (scope) {
            scope.$watch('arg', function (arg) {
                scope.fun(arg);
            });
        }
    };
});

Here is a little fiddle with a basic use case. http://jsfiddle.net/HB7LU/2677/

Upvotes: 0

Views: 66

Answers (1)

Gilad Peleg
Gilad Peleg

Reputation: 2010

The $scope function isn't being called because you are parsing it wrong.

To parse a function you need to assign it like so:

<directive arg="arg" fun="myFunction()"></directive>

If you want to pass arguments to it, you need to be just a little more careful. First you need to describe the arguments in advance like so:

<directive arg="arg" fun="myFunction(arg)"></directive>

and when you're calling the function inside the directive you apply it like so:

scope.fun({arg: arg});

I created a jsFiddle that solves your issue: jsFiddle

Please note that your own fiddle had a recursive call in it: everytime you increase arg you also trigger the $watch and so it went into a loop. I changed that a bit (since I know you made it just to show your example.

If you want to learn a bit more about the & parsing in directives, check out this video which I highly recommend: egghead.io isolate scope &

Upvotes: 2

Related Questions