Call a Directive Controller's method from Parent Controller in AngularJS

前端 未结 2 561
轻奢々
轻奢々 2021-01-03 06:45

I am using AngularJS and I have a directive which has its own Controller. It inherits the scope of the Parent Controller.

As an example, consider the following:

2条回答
  •  说谎
    说谎 (楼主)
    2021-01-03 07:28

    This is similar to what rajkamal is saying, in that you'll need to use broadcast... however you'll want to dynamically change the broadcast to target whichever child you need to.

    Here is a plunker showing an example

    And here's the code:

    app.controller('MainCtrl', function($scope) {
    
      // a method that broadcasts to a selected child.
      $scope.broadcastToSelectedChild = function (){
        $scope.$broadcast('call-' + $scope.broadcastTo);
      };
    });
    
    app.directive('testDir', function (){
      return {
        restrict: 'E',
        scope: {
          'name': '@'
        },
        template: '
    {{name}} called: {{called}}
    ', link: function(scope, elem, attr) { scope.called = false; //a child function to call. scope.childFunction = function (){ scope.called = true; }; //set up the name to be used as the listened to event. var removeOn; scope.$watch('name', function(v) { if(removeOn) removeOn(); removeOn = scope.$on('call-' + scope.name, function (){ scope.childFunction(); }); }); } }; });

    and here it is in HTML:

      

    What I did here is create a mechanism by which I can name my directives, and then broadcast to them by name. If the code isn't self explanatory, let me know. I hope this helps.

提交回复
热议问题