0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I had this idea from here: egghead.io/lessons/angularjs-isolate-scope-expression-binding Great, thanks. Its working. Sorry, for the mistakes.

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.