简体   繁体   English

嵌套指令之间的通信不起作用

[英]communication between nested directives not working

I have a directive Foo in Directive Bar i am trying to call a function in Foo 我在指令栏中有指令Foo,我正在尝试在Foo中调用函数

but it is not working. 但它不起作用。

http://jsfiddle.net/4d9Lfo95/3/ 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 UI看起来像这样

 <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! 找不到指令'uiBar'所需的控制器'uiFoo'!

The problem is that the require hierarchy searches up the tree, not down it. 问题是require层次结构在树上向上搜索,而不是在树上向下搜索。 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. 因此, ui-bar试图在其祖先之一而不是其子孙中找到一个uiFoo指令控制器,或者在其自身上(带有^符号)。

If you want to call a method from the child directive, just use the scope: http://jsfiddle.net/4d9Lfo95/5/ 如果要从child指令调用方法,只需使用范围: 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();
        }

      }
    };
  }
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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