AngularJS Service Only Running The First Time Controller Is Used
I have the following controller that uses a service Customers to return customers. The problem is that its only executing the service the first time the controller is run. Looking
Solution 1:
Angular .factory is a singleton so it will always only run once. Also, the $http
call is async so you should be using promise
in order to get the data to your controller. Try the following:
.factory('Customers', function($http, $q){
return function () {
var d = $q.defer();
$http.get('/api/customer')
.success(function(data) {
d.resolve(data);
})
.error(function(data){
console.log('error: ' + data);
d.reject(data);
});
return d.promise;
};
});
and in your controller:
.controller('searchCTRL', ['$scope', '$http', 'Customers', function($scope, $http, Customers) {
Customers().then(function (data) {
$scope.customers = data;
});
...
As $http
returns a promise, you can further simply your .factory
by doing:
.factory('Customers', function($http){
return function () {
return $http.get('/api/customer');
};
})
For more detail, see documentation for $http.
Post a Comment for "AngularJS Service Only Running The First Time Controller Is Used"