I was looking for a solution about polling data using AngularJS and I found here at stackoverflow.
In this solution (shown bellow) it is used a javascript object to return the response (data.response
) and if I try to replace that data
object for a simple javascript array it doesn't work, I would like to know exactly why I need to go with dot notation and why a single array doesn't work? (It would be great links or explanation with examples)
app.factory('Poller', function($http, $timeout) {
var data = { response: {}, calls: 0 };
var poller = function() {
$http.get('data.json').then(function(r) {
data.response = r.data;
data.calls++;
$timeout(poller, 1000);
});
};
poller();
return {
data: data
};
});
Trying to summarize my goal (what I want to really understand): where is var data = { response: {}, calls: 0 };
could be var data = {};
and then the response.data
would be setted directly to data data = r.data
and return {data: data};
, why do I need to rely on dot notation?
Let's say if we change the factory in this way:
In the controller, the statement
$scope.data = Poller;
assign d object to $scope.data, so the object relationship is like this after the initializationWhen poller() is called again in 1 sec, d is replaced with an new object, so the object relationship will be
so the angularjs's data binding will be broken since there is no way to trace to the r.data since d* is a brand new object with different prototype.
With dot notation, after the initialization the object relationship never changes since the periodic calls to poll() doesn't create new object
d
but it just keeping updating the response field with newr.data
object.