从指令中定义的控制器访问范围变量的正确方法是什么?
例如,我想让 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>