加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 17:41:33 所属栏目:安全 来源:网络整理
导读:我有一个角度控制器: .controller('DashCtrl',function($scope,Auth) { $scope.login = function() { Auth.login().then(function(result) { $scope.userInfo = result; }); };}); 哪个使用我创建的服务: .service('Auth',function($window) { var authCon
我有一个角度控制器:

.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();
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读