Why is it necessary to use a timeout in angular

This is probably the complete newb question ... an apology, but I can't put it into my head.

In many angular docs / examples, I see asynchronous functions wrapped in timeout blocks. Many of them are wrapped in setTimeout () and require explicit use.

if (!$scope.$$phase) {
    $scope.$apply();
}

Given that angular provides $ timeout, the above code just seems to be outdated or incorrect, and inside of angular, $ timeout should always be preferred. However, I am distracted.

Here is an example code snippet taken from: http://markdalgleish.com/2013/06/using-promises-in-angularjs-views/

var myModule = angular.module('myModule', []);
// From this point on, we'll attach everything to 'myModule'

myModule.factory('HelloWorld', function($timeout) {
  var getMessages = function(callback) {
    $timeout(function() {
      callback(['Hello', 'world!']);
    }, 2000);
  };

  return {
    getMessages: getMessages
  };
});

- , . - , ? :

var myModule = angular.module('myModule', []);
// From this point on, we'll attach everything to 'myModule'

myModule.factory('HelloWorld', function() {
  var getMessages = function(callback) {
    callback(['Hello', 'world!']);
  };

  return {
    getMessages: getMessages
  };
});

?

+4
2

$timeout $interval , . :

  • $apply
  • $apply

$rootScope $rootScope.$digest(), , $digest.

Angular . , , , , .

$digest . , , , , - , Angular , $digest, .

0

$timeout , , async, $http.get. , $timeout not setTimeout: $timeout angular $scope.$apply()

:

$scope.func = function(){
    $scope.showSomeLoadingThing = true;
    //Do some long-running stuff
    $scope.showSomeLoadingThing = false;
}

thingy , :

$scope.func = function(){
    $scope.showSomeLoadingThing = true;
    $timeout(function(){
        //Do some long-running stuff
        $scope.showSomeLoadingThing = false;
    });
}
0

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


All Articles