javascript - 使用 Angular js中的服务更新范围变量

标签 javascript angularjs angularjs-scope

我是 Angular 的初学者。我一直在更新 Angular js 中的 $scope 变量。我创建了一个服务名称“Main”,我想用它来更新我的 $scope.token。我使用了 $scope.apply 和 $scope.digest 但收到以下错误:

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

以下是代码片段。

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;
           }
};
}]);

在controllers.js

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

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

最佳答案

您的错误是由您在 Controller 中调用 $scope.$apply() 引起的。

而不是这个:

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

只需这样做:

$scope.token = Main.tokShowhide();

关于javascript - 使用 Angular js中的服务更新范围变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33190395/

相关文章:

javascript - 将参数传递给 HTML 以控制字体大小

javascript - 不将我的值从按钮和文本发送到我的 js 文件

javascript - Webpack 在与 typescript 的 react 中抛出错误 "You may need an appropriate loader"

AngularJS - 自己的过滤器

javascript - ng-bind-html html 与 css 不起作用

javascript - 问 :500 (Internal Server Error) at $http put?

angularjs - 如何在 Angular 指令中绑定(bind) bool 值?

javascript - AngularJS 过滤器 ng-repeat 不更新所有列

javascript - parse.com 行更新 javascript

javascript - 自动完成,自动更正在使用 cordova 或 javascript 的 android 4.4 中不起作用