Stefan
Stefan

Reputation: 1071

loop function through nested directive - angularjs

I try to loop a function through a nested directive. From the console.info in myCtrl I would expect the string "this should be logged".

angular.module('myApp')
      .controller('myCtrl', function ($scope) {
        $scope.aFunction = function(input) {
          console.info(input.message);
        }
      })
      .directive('levelOneDirective', function () {
        return {
          templateUrl: '<level-two-directive aFunction="aFunction(object)"></level-two-directive>',
          restrict: 'EA',
          scope: {
            aFunction:"&"
          },
          link: function (scope, element, attrs) {
          }
        };
      })
      .directive('levelTwoDirective', function () {
        return {
          templateUrl: '<div ng-click="aFunction({message: 'this should be logged'})"></div>',
          restrict: 'EA',
          scope: {
            aFunction:"&"
          },
          link: function (scope, element, attrs) {
          }
        };
      });

And in my index.html I have something like:

<div ng-controller="myCtrl">
  <level-one-directive aFunction="aFunction(object)"></level-one-directive>
</div>

But the console says undefined.

How to connect a function through nested directives?

Upvotes: 0

Views: 78

Answers (1)

Omri Aharon
Omri Aharon

Reputation: 17064

You have several mistakes in your code but I assume it's because you try to adjust it to the question (such as aFunction as attribute instead of a-function and templateUrl instead of template).

You can have a 2-way binding (=) in your directives (both of them):

scope: {
     aFunction:"="
},

And pass the function reference without the object:

<level-one-directive a-function="aFunction"></level-one-directive>

In the second directive HTML have:

<div ng-click="invokeFunction()"></div>

And then in the link function of your 2nd directive you can do:

scope.invokeFunction = function () {
    scope.aFunction({message: 'this should be logged'});
}

The above works and I find it more convenient than & binding, which as you can see, is not quite easy to work with, and frankly I haven't messed around enough with it to figure out how (and if possible) to pass arguments through it.

I've seen this question, but it's binding straight on the link function, and you want it with an ng-click so it might not work for you. But perhaps you'll find your solution there.

Upvotes: 1

Related Questions