对于我写的指令,如何获得$ scope,所以我可以做$ scope。$ on()?我可以注入$ rootScope,但我想使用$ scope来捕获广播。
angular.module('monitorApp')
.run(function($rootScope, $interval) {
$interval(function(){
$rootScope.$broadcast('ONE_SEC');
}, 1000);
});
angular.module('monitorApp')
.directive("countDown", [ 'sseHandler', function (sseHandler) {
console.log(sseHandler.broadcastStamp.cpuResult);
return {
scope: {
countFrom: "="
},
link: function(scope, $scope){
scope.countFrom = sseHandler.broadcastStamp.cpuResult;
$scope.$on('ONE_SEC', function(scope) {
sseHandler.broadcastStamp.cpuResult--;
});
}
}
}]);
UPDATE :使用范围注入,我收到错误:
Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <- countDownDirective
angular.module('monitorApp')
.directive("countDown", [ 'sseHandler', '$scope', function (sseHandler, $scope) {
console.log(sseHandler.broadcastStamp.cpuResult);
return {
scope: {
countFrom: "="
},
link: function(scope, $scope){
scope.countFrom = sseHandler.broadcastStamp.cpuResult;
$scope.$on('ONE_SEC', function(scope, $scope) {
sseHandler.broadcastStamp.cpuResult--;
});
}
}
}]);
答案 0 :(得分:5)
您可以使用scope.$on
,您无需尝试注入$scope
:
scope.$on('ONE_SEC', function() {
//do stuff
});
答案 1 :(得分:0)
该链接按顺序给出参数范围,元素和属性。在您的链接中,您实际上是将element
分配给$scope
要注入$ scope,你将它注入你注入ssehandler的同一个地方
directive("countDown", [ 'sseHandler', '$scope', function (sseHandler, $scope)....