angularjs auto reload when backend change

user3486836 picture user3486836 · Oct 22, 2015 · Viewed 40.9k times · Source

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

Answer

David Boskovic picture David Boskovic · Oct 22, 2015

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();
});