2017-05-30 47 views
0

我在指令欄中有一個僞指令Foo我想在Foo中調用一個函數嵌套指令之間的通信不工作

但它不起作用。

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

例如小提琴被創建。

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']); 

,其中作爲UI看起來像這樣

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

回答

0

你忽略了此錯誤消息:

控制器 'uiFoo',由指令所要求的 'uiBar',不能找到了!

問題是,require層次結構搜索樹而不是向下搜索。因此,ui-bar正試圖在它的祖先之一中找到一個uiFoo指令控制器,或者(在^的符號上)找到它的一個指令控制器,而不是其中的一個子項。

如果你想打電話從孩子指令的方法,只是使用範圍: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(); 
     } 

     } 
    }; 
    } 
); 
+0

三江源這是正確的。 –