從指令中定義的控制器訪問範圍變量的正確方法是什麼?從指令控制器訪問範圍
例如,我想讓父指令的控制器上的click事件調用函數。在父指令中,我希望控制器能夠訪問「常量」,FOO_VIEW,BAR_VIEW,BAM_VIEW
將這些常量放在頂層控制器中,在這種情況下,SearchCtrl(未顯示) ?
指令:
.directive('usersAndApps', function() {
return {
restrict:'EA',
scope: true,
controller: function() {
this.toggleView = function(viewName){
console.log('show view ' + viewName);
}
},
link:function(scope, elem, attrs) {
scope.FOO_VIEW = 'fooView';
scope.BAR_VIEW = 'barView';
scope.BAM_VIEW = 'bamView';
}
}
}).directive('usersAndAppsNav', function() {
return {
restrict: 'AE',
require:'^?usersAndApps',
replace:true,
scope:true,
link:function(scope,elem,attrs,usersAndAppsCtrl){
scope.toggleView = function(viewName){
usersAndAppsCtrl.toggleView(viewName);
}
},
templateUrl:'partials/usersAndApps/throwmeaway'
}
});
模板:
<div>
<button class="btn btn-large btn-primary" ng-click="toggleView(FOO_VIEW)">Foo View</button>
<button class="btn btn-large btn-primary" ng-click="toggleView(BAR_VIEW)">Bar View</button>
<button class="btn btn-large btn-primary" ng-click="toggleView(BAM_VIEW)">Bam View</button>
</div>
指令和嵌套(子)指令:
<div ng-controller="SearchCtrl">
<users-and-apps>
<users-and-apps-nav></users-and-apps-nav>
</users-and-apps>
</div>
這些都是很棒的視頻,你說得對。我正在尋找一些更具體的東西,特別是因爲這個特定的問題涉及操縱DOM,應該在指令級完成。 – binarygiant
我鏈接到的視頻講述了調用控制器方法的指令 - 是不是你所問的?他有關於指令 - >指令通信的另一個視頻@ http://www.egghead.io/video/rzMrBIVuxgM –
不是我正在尋找的。我更感興趣的是與指令的控制器交談的指令(作爲其他指令的API公開,通過require:'^?myDirective)與它交談。請參閱上面的代碼片段。再次感謝您的建議。我實際上正在研究一些事情,並且在某個時候我會有足夠的信息來回答這個問題(在egghead視頻之類的幫助下)。再次感謝! – binarygiant