Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular.js How to Inject $scope into directive() for $scope.on()?

Tags:

angularjs

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--;
           });
        }
    }
}]);
like image 616
dman Avatar asked Jul 22 '14 23:07

dman


People also ask

What is the scope of $scope in AngularJS?

$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.

Can we use $scope in a service AngularJS?

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).

How do you access $scope in console?

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 .

Can $scope be injected while creating service?

Explanation: No, the '$scope' cannot be injected while creating service using 'factory' method.


1 Answers

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/

like image 141
dave Avatar answered Sep 28 '22 01:09

dave