简体   繁体   中英

communication between nested directives not working

I have a directive Foo in Directive Bar i am trying to call a function in Foo

but it is not working.

http://jsfiddle.net/4d9Lfo95/3/

example fiddle is created.

angular.module('ui', []).directive('uiFoo',
function() {
    return {
        restrict: 'E',
        template: '<p>Foo</p>',
        link: function($scope, element, attrs) {
            $scope.message = function() {
                alert(1);
            };
        },
        controller: function($scope) {
            this.message = function() {
                alert("Foo Function!");
            }
        }
    };
}
).directive('uiBar',
function() {
    return {
        restrict: 'E',
        template: '<button ng-click="callFunction()">Bar</button> <ui-foo></ui-foo>',
        require: 'uiFoo',
        scope: true,
        link: function($scope, element, attrs, uiFooController) {
            $scope.callFunction = function() {
                alert('Bar Function');
                uiFooController.message();
            }

        }
    };
}
);angular.module('myApp', ['ui']);

where as the UI looks like this

 <div ng-app="myApp">  <ui-bar>  </ui-bar></div>

You left out this error message:

Controller 'uiFoo', required by directive 'uiBar', can't be found!

The problem is that the require hierarchy searches up the tree, not down it. So, ui-bar is trying to find a uiFoo directive controller either on itself or (with the ^ symbol) in one of it's ancestors, not one of it's children.

If you want to call a method from the child directive, just use the scope: http://jsfiddle.net/4d9Lfo95/5/

angular.module('ui', []).directive('uiFoo',
  function() {
    return {
      restrict: 'E',
      template: '<p>Foo</p>',
      controller: function($scope) {
        $scope.message = function() {
          alert("Foo Function!");
        }
      }
    };
  }
).directive('uiBar',
  function() {
    return {
      restrict: 'E',
      template: '<button ng-click="callFunction()">Bar</button> <ui-foo></ui-foo>',
      scope: true,
      controller: function($scope) {
        $scope.callFunction = function() {
          alert('Bar Function');
          $scope.message();
        }

      }
    };
  }
);

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