kidwon
kidwon

Reputation: 4524

Pass resource from directive to controller

I am trying to expose a resource from directive scope to a controller scope by calling a provided in the view callback. However the argument variable is undefined. What am I missing?

Here's a fiddle example: https://jsfiddle.net/xqknpe5d/

View

<div on-my-event="doStuff(foo)"></div>

Directive

App.directive('myDirective', ['$whateverModule', function($module) {
  return {
    restrict: 'A',
    scope: {
      onMyEvent: '&'
    },
    link: function(scope, element, attrs) {          
      (scope.onMyEvent) && ( scope.onMyEvent('moo') );         
    }
  };
}]);

Controller

ctrls.controller('myController', ['$scope', function($scope) {
  $scope.doStuff = function(foo) {
    console.log('moo: ', foo);
  };
}]);

Appreciate your kind help

Upvotes: 0

Views: 59

Answers (1)

Ilya Dmitriev
Ilya Dmitriev

Reputation: 1720

Call function onMyEvent like this in your link function of your directive. You have to send object with name of parameter('foo') as key and 'moo' as value.

link: function(scope, element, attrs) {          
        (scope.onMyEvent) && ( scope.onMyEvent({foo: 'moo'}) );         
    }

Read more about & binding here.

Upvotes: 2

Related Questions