sukesh
sukesh

Reputation: 2437

Setting a time delay in angularjs

I would like to push the data into the array after a 2 second delay each time.

//working code

$scope.GetData = function(){
  DataFactory.GetCategories()
  .success(function(data,status){
    $scope.TheArray.push(data);
   })
}

//This doesnt work. No data is shown in html

$scope.GetData = function(){
  DataFactory.GetCategories()
  .success(function(data,status){
    setTimeout(function() {
       $scope.TheArray.push(data);
     }, 2000);    
   })
}

EDIT:

$scope.GetData = function(){
  DataFactory.GetCategories()
  .success(function(data,status){
    $timeout(function () {
                        $scope.ChatHistory.push(JSON.parse(JSON.parse(data)));
                    }, 3000);    
   })
}

Upvotes: 0

Views: 600

Answers (1)

Abhishek Jain
Abhishek Jain

Reputation: 2977

Use $timeout instead of setTimeout, and it will run fine. When using setTimeout, you will have to do $scope.$apply to propogate your changes to your view/model, but $timeout does that magic for you, so you don't have to worry about it.

More info on $timeout here

EDIT: You will have to add $timeout as a dependency, like below

angular.module('myApp').controller('MyController', function($timeout) {
$scope.GetData = function(){
  DataFactory.GetCategories()
  .success(function(data,status){
    $timeout(function () {
                        $scope.ChatHistory.push(JSON.parse(JSON.parse(data)));
                    }, 3000);    
   })
}
})

Upvotes: 2

Related Questions