0
votes

I have a directive inside another directive. Outer directive shares its scope with controller, while inner one has its own. I'd like to pass a reference to controller's function to inner directive so it can be called from there. But I cannot figure out how to pass the function and its parameters to inner directive so it can properly call the controller's function.

Here is planker to illustrate my problem.

If you click on "Dir 2 Click me" the alert says the parameters have came undefined.

3

3 Answers

3
votes

You can pass in the outer controller method using '=' and adjust the code accordingly...

angular.module('app', [])
    .controller('ctrl', function($scope){
        $scope.myCtrlMethod = function(msg, b) {
            alert(msg + ' and b='+b);
        };
    })
    .directive('dir1', [function(){
        return {
            restrict: 'E',
            replace: true,
            template: '<div><p ng-click="myDir1Method(\'my dir1 method\',\'b\')">Dir 1 Click me</p><dir2 my-ctrl-method="myCtrlMethod"></dir2></div>',
            link: function(scope, elem, attrs){
                scope.myDir1Method = function(msg,b){
                    scope.myCtrlMethod(msg, b);
                };
            }
        };
    }])
    .directive('dir2', [function(){
        return {
            restrict: 'E',
            scope: {
                myCtrlMethod: '='
            },
            replace: true,
            template: '<p ng-click="myDir2Method(\'my dir2 method\',\'b\')">Dir 2 Click me</p>',
            link: function(scope, elem, attrs){
                scope.myDir2Method = function(msg,b){
                    scope.myCtrlMethod(msg, b);
                };
            }
        };
    }]);

Plunker: http://plnkr.co/edit/xbSNXaSmzWa3G1GSH6Af?p=preview

Edit: '=' evaluates the expression in the context of the parent scope and its result is bound to the property on the inner scope. In this example, 'myCtrlMethod' is evaluated against the parent scope, which returns myCtrlMethod from the parent scope (a function). This function is bound to myCtrlMethod on the inner scope, and can be invoked with scope.myCtrlMethod(msg, b).

2
votes

you can use controller as a reference to your directive

See: http://jsbin.com/vayij/1/edit

directive('sonDirective', function(){
  return {
         restrict: 'E'
         scope: {},
         replace: true,
         template: '<div....'
         controller: 'MainController' //controller as a reference 
      }
})
0
votes

Just put the controller on the scope : $scope.$b=this;

See : http://plnkr.co/edit/skDF8D1scFJYrTUmcXIL?p=preview