Within the realm of AngularJS, I've implemented a factory as follows:
.factory('Users', function($http) {
var users = [];
return {
getUsers: function() {
return $http.get("data.json")
.then(function(response) {
users = response.data;
return users;
});
},
getUser: function(id) {
for (i = 0; i < users.length; i++) {
if (users[i].id == id) {
return users[i];
}
}
return null;
}
}
})
Subsequently, I proceed to load this data within my controller:
.controller('SessionsCtrl', function($scope, Users) {
$scope.users = Users.getUsers();
})
Strangely enough, upon console.logging the response from the HTTP request, the data is retrieved successfully, yet the scope data refuses to update.
I've come across instances where the controller structure is slightly altered, resembling the following:
Users.getUsers().then(function(data) {
$scope.users = data;
});
Despite my understanding that $http
already provides a promise, it prompts me to question whether I am overlooking something vital. Would the utilization of $q
be necessary at all in this scenario?