简体   繁体   中英

Call parent controllers' function from directive in angular

jsfiddle

I have a ng-click within a directive named ball . I am trying to call MainCtrl 's function test() and alert the value of ng-repeat's alignment of ball. Why cant i recognize the MainCtrl's test function? var $scope; var app = angular.module('miniapp', []);

app.controller('MainCtrl', function($scope) {
    $scope.project = {"name":"sup"};

    $scope.test = function(value) {
        alert(value);   
    }
    $scope.test2 = function(value) {
        alert('yo'+value);   
    }

}).directive('ball', function () {
        return {
            restrict:'E',
            scope: {
                'test': '&test'
            },
            template: '<div class="alignment-box" ng-repeat="alignment in [0,1,2,3,4]" ng-click="test(alignment)" val="{{alignment}}">{{alignment}}</div>'

        };
    });

html

<div ng-app="miniapp">
   <div ng-controller="MainCtrl">
       {{project}}
       <ball></ball>
   </div>
</div>

You need to pass the test() method from the controller into the directive...

<div ng-app="miniapp">
   <div ng-controller="MainCtrl">
       {{project}}
       <ball test="test"></ball>
   </div>
</div>

Change & to = in directive:

scope: {
    'test': '=test'
}

Fiddle: http://jsfiddle.net/89AYX/49/

the one way is to not isolate a directive scope...just remove the scope object from directive.

Another way is to implement an angular service and put a common method there, inject this service wherever you need it and in the directive call function that will be insight isolated scope and there call a function from directive

You just need to set the controller in your directive as: controller: 'MainCtrl'

so the code for your directive should look like:

return {
    restrict:'E',
    scope: {
        'test': '&test'
    },
    template: '<div class="alignment-box" ng-repeat="alignment in [0,1,2,3,4]" ng-click="test(alignment)" val="{{alignment}}">{{alignment}}</div>',
    controller: 'MainCtrl'

};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM