I'm developing a small AngularJS app and I'm currently struggling with creating a service.
I have a service that serves as a backend for providing contacts (name, address...).
Until now they were hard-coded as an array in the service (instance.contacts=[...]
), but now I'm trying to read them from a json file :
myModule.factory('contactService', ['$http',function ($http) {
var instance = {};
$http.get('contacts.json').success(function (data) {
instance.contacts = data;
});
return instance;
}]);
I see in my browser console that the file has been read successfully, but I don't see any change on-screen.
So I tried the following instead, and it worked :
myModule.factory('contactService', ['$http',function ($http) {
var instance = {
contacts:[]
};
$http.get('contacts.json').success(function (data) {
angular.forEach(data, function(item) {
instance.contacts.push(item);
});
});
return instance;
}]);
I don't know why the second code snippet works, and not the first. Could someone please help me understand ?
No comments:
Post a Comment