Automatically reload angularjs when changing backend

I need to auto-update in my application when background changes change. I added a button to reload the GET for my back-end, but I do not want to do this. 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

+6
source share
2 answers

You can simply reload your data at regular intervals. Otherwise, you need to configure something like socket.io or Pusher and click on notifications in the browser when updating the server.

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

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 should be explicitly destroyed when you are done with them. In particular, they are not automatically destroyed when a control area or control is destroyed. You must take this into account and be sure to always cancel the interval at the appropriate time.

+7
source

All Articles