K
K
Karina2015-09-11 00:20:03
JavaScript
Karina, 2015-09-11 00:20:03

How to change a variable asynchronously in angular?

I usually did this:

var app = angular.module('myApp', []).controller('myCtrl', ['$scope', function($scope) {
  $scope.authorizedApp = false;

  $scope.example = function () {
  $scope.authorizedApp = true; //так меняла значения переменных
}
}]);

And already in the template it was possible to use all sorts of directives (ng-if, etc.).
But now I'm working with facebook api. and there is a bunch of asynchronous calls.
Apparently, asynchronous functions are still running (inside these functions I change the $scope.authorizedApp variable), and my template has already been loaded and $scope.authorizedApp takes on a global value.
What can you think of?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
Drm, 2015-09-11
@iKapex

For asynchronous requests, you should use the so-called promises (promice), in angular they are in the $q library

A
Alexander Wolf, 2015-09-11
@mannaro

$scope.$digest();
in the end, call and you will be happy)

D
DigitalSmile, 2015-09-11
@DigitalSmile

From the obvious solutions to me, don't use global variables. At you one value is dragged on inheritance in all controlers?

K
Karina, 2015-09-12
@iKapex

The $q library is really what you need.
It is done like this:

$scope.example = function (value) { 
  var q = $q.defer();
  if (value == 'what_you_need') {
     q.resolve(variable); //подставляете в variable значение, которое вам надо
  }
  else {
    q.reject(variable);  //подставляете в variable значение, которое вам надо в противных случаях     
  }
  return  q.promise;
}

and already in the callback you create the following chain:
$scope.auth = false;  //эта переменная и примет значение, когда callback отработает
$scope.promise = $scope.example(your_variable);
    $scope.promise.then ( function (v) { $scope.auth = v },
                          function (err) { $scope.auth = err }                 
        								)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question