Reputation: 2588
I feel like I'm missing something simple here. My goal is to be able to access data from a service (which gets data from an endpoint) but later be able to update that stored data by re-pinging the endpoint.
.service('myService', function($http) {
var self = this;
this.myData = {};
this.getItem = function() {
return $http.get('/path/to/endpoint')
.then(function(res) {
self.myData = res.data; // data looks like: { x: 1, y: 2}
});
};
})
.controller('mainCtrl', function($scope, myService) {
myService.getItem();
$scope.data = myService.myData;
window.logService = function() {
console.log(myService); // { getItem: function(){...}, data: {x: 1, y: 2} }
};
});
<div ng-controller="mainCtrl">{{data.x}}</div> <!-- Does not update with the data returned from the promise -->
This seems to make no sense. If I hit window.logService()
after the promise returns, I clearly see the data in the correct spot, yet my view will not update.
Upvotes: 0
Views: 84
Reputation: 40863
Angular is watching the {}
reference even after you reassign the value.
Try using angular.copy()
in the call back so the watched object gets updated and your view updates correctly.
.then(function(res) {
angular.copy( res.data, self.myData);
});
Upvotes: 1