我有一个ng-repeat创建多个指令,每个指令都有一个独立的范围。我希望能够调用在每个指令上调用函数的单个函数,因此它会在每个隔离的作用域上重置一个变量。无论如何我无法解决这个问题?我意识到这可能不是最佳实践,但我现在只需要一个解决方案。
答案 0 :(得分:1)
我使用的另一种选择是角度事件系统。
我正在创建一个小部件仪表板。我的小部件是Failed to get DB handle: could not find driver
中包含的指令。
我在控制器ng-repeat
中发出事件,然后使用$scope.$broadcast
收听我的指令。我使用$scope.$on
的{{1}}来定位特定的小部件。
快速示例小提琴:http://jsfiddle.net/adyjm9g4/
编辑:忘记提及您也可以传递数据:http://jsfiddle.net/adyjm9g4/1/
答案 1 :(得分:0)
一种方法是提供对将执行某些功能的指令(即scope: { xxx: '&' }
)的回调。可能是:
<the-directive callback="ctrl.command(action, argument)" />
该指令如下:
app.directive('theDirective', function() {
return {
...
scope: {
callback: '&',
...
},
controller: ['$scope', function($scope) {
this.resetTheVariable = function() {
// DO WHAT YOU WANT HERE
};
$scope.callback({ action: 'register', argument: this });
$scope.$on('$destroy', function() {
scope.callback({ action: 'deregister', argument: this });
});
}]
};
})
现在调用此指令的控制器如下所示:
function TheController() {
var registeredDirectives = [];
this.command = function(action, argument) {
switch(action) {
case 'register':
registeredDirectives.push(argument);
break;
case 'deregister':
var index = registeredDirectives.indexOf(argument);
if( index >= 0 ) {
registeredDirectives.splice(index, 1);
}
break;
}
};
this.resetAll = function() {
registeredDirectives.forEach(function(registeredDirectiveController) {
registeredDirectiveController.resetTheVariable();
});
};
}