0

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);    
   })
}
1
  • @RobJ, he doesn't want to push data every 2 seconds, but just once after a 2 second delay. $interval will cause the data to be added every 2 seconds. Commented Jan 28, 2015 at 14:04

1 Answer 1

2

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);    
   })
}
})
Sign up to request clarification or add additional context in comments.

1 Comment

you will have to add it as a dependency on your controller

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.