for the directive I wrote, how do I get $scope in there so I can do $scope.$on()? I could inject $rootScope, but I want to use $scope to catch the broadcast.
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: with scope injection, I get error:
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--;
});
}
}
}]);
$scope is a child object that is used to bind the HTML(view) & Javascript(Controller) in a webpage. It is created with the ng-app directive. It is created with the ng-controller directive. It is available globally for all the controllers, i.e, the property assigned with “$rootscope” can be used anywhere.
Services are singletons, and it is not logical for a scope to be injected in service (which is case indeed, you cannot inject scope in service).
scope(); $('#elementId'). scope(). $apply(); Another easy way to access a DOM element from the console (as jm mentioned) is to click on it in the 'elements' tab, and it automatically gets stored as $0 .
Explanation: No, the '$scope' cannot be injected while creating service using 'factory' method.
You can just use scope.$on
, you don't need to try and inject $scope
:
scope.$on('ONE_SEC', function() {
//do stuff
});
Example: http://jsfiddle.net/G2r7G/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With