1

When just passing a callback from a page template (with a controller), this answer explains correctly how to format the usage of the callback in the directive template with the value as a JSON object, like this:

<a data-ng-click="callback({image: url})"></a>

But what happens if the directive is just passing on the callback to another directive.
Should it just pass the callback like this:

<another-directive data-ng-click="callback()"></another-directive>

Or should it pass the same object format like this:

<another-directive data-ng-click="callback({image: url})"></another-directive>

Or another option?
Right now non of these works for me.

Ron Harlev
  • 16,227
  • 24
  • 89
  • 132

1 Answers1

2

I think I understand what you're trying to accomplish, so I'll give an example.

You have a controller (myController) that calls a directive (myDirective) that calls another directive (anotherDirective), and you want to pass a "callback" function from myController through myDirective down to anotherDirective. Here is how you can do it:

angular
  .module('myApp', [])
  .controller('myController', ['$scope', function($scope) {
    $scope.foo = function(param) {
      alert('This function is declared on the main controller but called from a directive a few levels deep.  Parameter: ' + param);
    };
  }])
  .directive('myDirective', function() {
    return {
      template: `
        <h1>My Directive</h1>
        <another-directive callback="myFunction(b)"></another-directive>
      `,
      scope: {
        myFunction: '&'
      }
    }
  })
  .directive('anotherDirective', function() {
    return {
      template: `
        <h2>Another Directive</h2>
        <button data-ng-click="callback({b: {a: 'hello world'}})">Click Me</button>
      `,
      scope: {
        callback: '&'
      }
    }
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myController">
  <my-directive my-function="foo(a)"></my-directive>
<div>

The key to this starts in the lowest level directive anotherDirective:

<button data-ng-click="callback({b: {a: 'hello world'}})">Click Me</button>

Now remember how callback was set on its parent:

<another-directive callback="myFunction(b)"></another-directive>

And how myFunction was initially declared on its parent:

<my-directive my-function="foo(a)"></my-directive>

I'm struggling to think of a way to explain it properly, but with this example you should be able to see the pattern with how the expressions bubble up to each parent.

jtate
  • 2,612
  • 7
  • 25
  • 35