Calling directive's methods from parent controller in AngularJS

后端 未结 5 1112
无人及你
无人及你 2021-02-03 22:59

I am using AngularJS with the alias controllers pattern. I can\'t access (or I don\'t know how to) directive methods from a parent controller.

I have a

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-03 23:50

    If you strictly want to use isolated scope inside a directive then the directive method can be only called by using angular events such as $broadcast & $emit

    In your case, you need to use $broadcast to send event to entire $rootScope

    You Code will become like this.

    Working Code Pen

    HTML

    {{ctrl.text}}

    CODE

    angular.module('myApp', []).
    
    controller('MyCtrl', function($rootScope){
      var that = this;
    
      this.text = 'Controller text';
    
      this.dirText = 'Directive text';
    
      this.click = function(){
          $rootScope.$broadcast('changeText',{});
      }
    }).
    
    directive('myDir', function(){
      return {
         restrict: 'E',
         scope: {
           text: '='
         },
         link: function(scope, element, attrs){
           scope.changeText = function(){
             scope.text = 'New directive text';
           };
             scope.$on('changeText',function(event, data){
                 scope.changeText()
             });
         },
         template: '

    {{text}}

    ' }; });

    Instead of calling method of child scope, you need to broadcast an event and that will have to be listened by the directive scope & it will fire changeText method after listening to that event.

    NOTE

    Using service / factory would be better approach.

    This would be hopefully help you. Thanks.

提交回复
热议问题