Confused the need for $ scope. $ apply

I have an angular controller:

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

What is the created service used for:

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

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

    };
});

The Auth service uses the Cordova plugin, which will be outside the angular world. I guess I don’t understand when you need to use $scope.$applyyour $ scope to update, and when not. My wrong assumption has been since I wrapped the logic in the angular service, then I will not need it in this case, but nothing will be updated if I do not complete the statement $scope.userInfo =in $timeoutor $scope.$apply.

Why is this necessary in this case?

+4
source share
2 answers

From the angular wiki :

AngularJS provides wrappers for common asynchronous JS behaviors:

...

jQuery.ajax() = > $http

async $scope. $apply() , AngularJS, .

, Auth angular $http, $scope.$apply() angular Async Auth.

AngularJS native. AngularJS (, ), $scope. $apply() , .

EDIT:

( ):

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

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

Angular , $scope.userInfo , $scope.$apply, $scope.

, $timeout . Angular setTimeout, $scope.$apply .

$scope.$apply() .

NB: $timeout .

+2

Source: https://habr.com/ru/post/1626441/


All Articles