10

I need in my app to auto refresh when the back-end changes. I added a button to reload the GET to my back-end but I don't wish do that. This is my code

<body data-ng-app="myPr">
  <div ng-controller="TodosController">
    <div ng-repeat="todo in todos">
      <p>{{todo.title}} ...... {{todo.is_completed}}</p>
    </div>
    <button ng-click="reload()">Reload</button>
  </div>
</body>

my app.js

var myPr = angular.module('myPr',[]);

myPr.controller("TodosController", function ($scope,$http){

  $scope.reload = function () {
    $http.get('http://localhost:3000/api/todos').
        success(function (data) {
          $scope.todos = data.todos;
      });
  };
  $scope.reload();
});

Thanks

2 Answers 2

16

You could just reload your data at regular intervals. Otherwise you'd need to setup something like socket.io or Pusher and push notifications to the browser when the server updates.

var myPr = angular.module('myPr',[]);

myPr.controller("TodosController", function ($scope,$http,$timeout){

  $scope.reload = function () {
    $http.get('http://localhost:3000/api/todos').
        success(function (data) {
          $scope.todos = data.todos;
      });

    $timeout(function(){
      $scope.reload();
    },30000)
  };
  $scope.reload();
});
Sign up to request clarification or add additional context in comments.

3 Comments

You should use $interval as in @Kelvin's answer. Timeout just execute once.
we can use $interval, But how to stop it?
it's actually working as an interval, to stop it you just need to use a flag to stop calling the timeout function.
12

You can use $interval(fuctionToRepeat, intervalInMillisecond) as documented here.

var myPr = angular.module('myPr',[]);

myPr.controller("TodosController", function ($scope,$http){

    $scope.reload = function () {
        $http.get('http://localhost:3000/api/todos').
            success(function (data) {
                $scope.todos = data.todos;
            });
    };
    $scope.reload();
    $interval($scope.reload, 5000);
});

Note: Intervals created by this service must be explicitly destroyed when you are finished with them. In particular they are not automatically destroyed when a controller's scope or a directive's element are destroyed. You should take this into consideration and make sure to always cancel the interval at the appropriate moment.

1 Comment

I used $interval, it's pretty good. Make sure to include decent interval time to prevent too much load on backend

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.