angularjs – 对$scope的需求感到困惑.$apply

前端之家收集整理的这篇文章主要介绍了angularjs – 对$scope的需求感到困惑.$apply前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个角度控制器:

.controller('DashCtrl',function($scope,Auth) {
    $scope.login = function() {
        Auth.login().then(function(result) {
            $scope.userInfo = result;
        });
    };
});

哪个使用我创建的服务:

.service('Auth',function($window) {
    var authContext = $window.Microsoft.ADAL.AuthenticationContext(...);

    this.login = function() {
        return authContext.acquireTokenAsync(...)
            .then(function(authResult) {
                return authResult.userInfo;
            });

    };
});

Auth服务使用的是Cordova插件,该插件位于角度世界之外.我想我不清楚何时你需要使用$scope.$apply来更新你的$scope,当你不需要时.我的错误假设是因为我将逻辑包装到一个角度服务中,然后在这个实例中我不需要它,但除非我将$scope.userInfo =语句包装在$timeout或$scope中,否则什么都不会更新.$apply.

为什么在这种情况下有必要?

解决方法

angular’s wiki开始:

AngularJS provides wrappers for common native JS async behaviors:

jQuery.ajax() => $http

This is just a traditional async function with a $scope.$apply()
called at the end,to tell AngularJS that an asynchronous event just
occurred.

所以我想因为你的Auth服务不使用angular的$http,$scope.执行Async Auth函数后,$apply()不会被angular调用.

Whenever possible,use AngularJS services instead of native. If you’re
creating an AngularJS service (such as for sockets) it should have a
$scope.$apply() anywhere it fires a callback.

编辑:

在您的情况下,一旦通过换行(如您所做)更新模型,您应该触发digest cycle

Auth.login().then(function(result) {
   $scope.$apply(function(){
      $scope.userInfo = result;
   });
});

要么

Auth.login().then(function(result) {
    $scope.userInfo = result;
    $scope.$apply();
});

猜你在找的Angularjs相关文章