Note that there are some explanatory texts on larger screens.

plurals
  1. POAngularJS watch json periodically
    primarykey
    data
    text
    <p>I try to get a json file via $http by calling a DataService periodically.</p> <p>Then I want to use the $watch functionality to react to any data change. However the watch function never gets triggered more than once. Why?</p> <pre><code>var app = angular.module('myApp', ['ngRoute']). config(['$routeProvider', function ($routeProvider) { //... }]) . run(function ($rootScope, $timeout, $location, DataService) { $rootScope.jsonData = {} var delaytime = 10 * 1000; $rootScope.jsonData = DataService.getData(); $timeout(function repeat() { console.log("in repeat") $rootScope.jsonData = DataService.getData(); $timeout(function () { console.log("in inner repeat") repeat(); }, delaytime ); }, delaytime ); console.log("xxx") console.log($rootScope.jsonData) $rootScope.$watch('jsonData', reactToDataChange($rootScope, $location)); }) ; function reactToDataChange($rootScope, $location) { console.log("yyy") console.log($rootScope.jsonData) // ... } </code></pre> <p>DataService:</p> <pre><code>app.service('DataService', function ($http) { var data = null; function setData(newdata) { data = newdata; } return { getData: function () { console.log("getting data"); var rand = "?rand=" + Math.random() * 10000; $http.get('data/bla.json' + rand, {cache: false}) .success(function (newdata) { console.log(newdata); setData(newdata); }) . error(function (data, status, headers, config) { console.log("error"); console.log(status) }); return data; } }; }); </code></pre> <p>Console shows:</p> <pre><code>getting data xxx null yyy null new data:[object Object] Object {bla: Object} in repeat getting data new data:[object Object] Object {bla: Object} in inner repeat in repeat getting data new data:[object Object] Object {bla: Object} in inner repeat in repeat ... </code></pre> <p>Why is yyy not shown again?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload