[英]Angular: Call directive controller function from separate controller
假設我有一個名為myApp的應用程序。 菜單組件有一個指令。 此指令具有定義的控制器。 現在,從另一個加載視圖的控制器中,我想調用該菜單指令的控制器的方法。
代碼看起來像什么呢? 其他控制器如何調用菜單指令的控制器上的方法?
我認為問題在於,當您應該將某個函數綁定到某個去往controller <- directive
委派調用時,您正在嘗試執行controller -> directive
controller <- directive
。
例如,您可以查看angular-ui / bootstrap的tabs指令 onSelect和onDeselect:
.directive('tab', ['$parse', function($parse) {
return {
require: '^tabset',
restrict: 'EA',
replace: true,
templateUrl: 'template/tabs/tab.html',
transclude: true,
scope: {
active: '=?',
heading: '@',
onSelect: '&select', //This callback is called in contentHeadingTransclude
//once it inserts the tab's content into the dom
onDeselect: '&deselect'
},
// etc.
使用&
表達式使您可以將函數綁定為回調。
這種用法的一個例子是目標控制器中的作用域綁定函數:
$scope.selectedTab = function(){ alert('woohoo'); };
在視圖中哪個“綁定”到指令的功能:
<tab select="selectedTab()">
tabs指令還有一個很好的示例,說明了如何在兩個不同的指令控制器之間進行通信。 請參見標簽集控制器的ctrl.select 。 一個tab
指令需要一個帶有require的父tabSet
控制器:
.directive('tab', ['$parse', function($parse) {
return {
require: '^tabset',
tab
指令可以訪問tabset
函數中的tabset
控制器的select函數:
compile: function(elm, attrs, transclude) {
return function postLink(scope, elm, attrs, tabsetCtrl) {
scope.$watch('active', function(active) {
if (active) {
tabsetCtrl.select(scope);
}
});
scope.disabled = false;
if ( attrs.disabled ) {
scope.$parent.$watch($parse(attrs.disabled), function(value) {
scope.disabled = !! value;
});
}
scope.select = function() {
if ( !scope.disabled ) {
scope.active = true;
}
};
tabsetCtrl.addTab(scope);
scope.$on('$destroy', function() {
tabsetCtrl.removeTab(scope);
});
//We need to transclude later, once the content container is ready.
//when this link happens, we're inside a tab heading.
scope.$transcludeFn = transclude;
};
}
因此,您有了如何在指令中發生某些動作的情況下,從某些非指令控制器執行代碼的方法,以及由於指令require
約束而如何執行某些指令間功能的方法。
編輯:對於任何感興趣的人,這里是指令表達式的文檔: http : //docs.angularjs.org/api/ng/service/ $ compile#comprehensive-directive-api
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.