简体   繁体   中英

updating scope variable using service in angular js

I am a beginner in Angular. I am stuck with updating $scope variable in angular js. I have created a service name "Main" with which I want to update my $scope.token. I have used $scope.apply and $scope.digest but receive the following error:

> Error: [$rootScope:inprog] $apply already in progress
> http://errors.angularjs.org/1.4.4/$rootScope/inprog?p0=%24apply
>     at angular.js:68
>     at beginPhase (angular.js:16273)
>     at Scope.$apply (angular.js:16014)
>     at new <anonymous> (controllers.js:11)
>     at Object.invoke (angular.js:4473)
>     at extend.instance (angular.js:9093)
>     at nodeLinkFn (angular.js:8205)
>     at compositeLinkFn (angular.js:7637)
>     at compositeLinkFn (angular.js:7641)
>     at publicLinkFn (angular.js:7512)

following are the code snippets.

index.html

 <div class="navbar-collapse collapse">
                    <ul class="nav navbar-nav">
                        <li><a ng-href="#/">Home</a></li>
                        <li data-ng-show="token"><a ng-href="#/me">Me</a></li>
                        <li data-ng-hide="token"><a ng-href="#/signin">Signin</a></li>
                        <li data-ng-hide="token"><a ng-href="#/signup">Signup</a></li>
                        <li ><a data-ng-show='true' ng-click="logout()">Logout</a></li>
                    </ul>
                </div>

services.js

'use strict';

angular.module('angularRestfulAuth')
    .factory('Main', ['$http', '$localStorage','$cookies', function($http, $localStorage,$cookies){
        return {
           tokShowhide: function(data) {
               if($cookies.get('sid')!=undefined)
               return true;
               else
               return false;
           }
};
}]);

In controllers.js

 $scope.$apply(function () {
            $scope.token = Main.tokShowhide();
        });

How do I update $scope variable and reflect its change in my view (index.html) ??

In which context are you executing that $apply() ?

If you're doing it inside of one of your functions of ng-click , on when the controller is being loaded (for instance when you are navigating after you clicked a link with a ng-href ), is not necessary to use $apply() , since you're already executing in angularJs context.

You need to call $apply() when you are outside angular context, for instance, if you are using a jquery event.

All the angularjs events ( ng-click , ng-mouseover , ng-mouseenter , ng-class ) are wrappers for different events or functionalities in pure Javascript plus the call of $apply() , so Angular knows that it must check $watchers and update the view. The same goes for built-in services of Angular.

In summary, you just need to do

$scope.token = Main.tokShowhide();

directly.

Your error is being caused by your call to $scope.$apply() in your controller.

Instead of this:

$scope.$apply(function () {
  $scope.token = Main.tokShowhide();
});

Just do this:

$scope.token = Main.tokShowhide();

I usually use $scope.$apply() if updating scope variables through something other than Angular's built-in services. Most commonly I see this when using something like jQuery to perform an async request and then wanting to update a scope variable with the result. However, if you are simply updating a scope variable without doing anything asynchronous, Angular has two-way data binding and these updates will normally be updated automatically on the view once changed.

If for some reason you update a scope variable, but it isn't updating on your view, you can try using $scope.$apply(), but I prefer to instead inject $timeout and then wrap the scope variable you are updating inside the $timeout service, like so:

$timeout(function(){
    $scope.token = Main.tokShowhide();
})

This will also trigger a new digest cycle and update your view with these new scope values and works when receiving the error you are describing about a digest cycle already in progress.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM