Stussa
Stussa

Reputation: 3415

AngularJS Directive Run Callback With Params

I've got a pretty simple directive that I'd like to be able to run a callback with parameters supplied by the directive and the scope. For example:

<div ng-repeat="user in users">
  <div sample="..." callback="welcome(user, $message)">
  </div>
</div>

I'm having trouble using $parse to handle this. My sample directive is as follows:

app.directive('sample', ['$parse', function ($parse) {
  return {
    restrict: 'A',
    scope: {},
    link: function (scope, element, attrs) {
      // ...
      function greet () {
        var callback = $parse(attrs.callback);
        callback(scope, { $message: 'Howdy' });
      }
    },
  },
}]);

However, despite getting a function from $parse - executing the function never results in my welcome function (defined in a controller) being called (note: on Angular 1.5.x). I'm assuming scope is wrong somehow (that it is using the isolated scope instead of the parent scope) - but I do need an isolated scope (simplified for example). What am I doing wrong?

Upvotes: 0

Views: 74

Answers (2)

Phil
Phil

Reputation: 164830

You may use the & isolate scope binding. I'd also provide the user object to your directive

return {
  restrict: 'A',
  scope: {
    user: '<',
    callback: '&'
  }
  link: function(scope) {
    // ...
    function greet() {
      scope.callback({
        user: scope.user,
        $message: 'Howdy'
      })
    }
  }
}

and

<div sample="..." user="user" callback="welcome(user, $message)">

Upvotes: 0

Kevin Sylvestre
Kevin Sylvestre

Reputation: 38032

Can you use scope.$parent as a parameter to your $parse call? You may also wish to wrap with a $scope.$apply(function () { ... });.

Upvotes: 2

Related Questions