To simplify your code, consider using an Angular service or factory to abstract the $http
call. By creating a service, you can ensure that your controllers consistently use the same interface.
Here is an example:
angular.module('myModule')
.service('myService', function ($http, $q) {
var myData = null;
this.get = function (params) {
return myData
? $q.when(myData)
: $http.get('http://example.com/myEndpoint', params)
.success(function (data) {
myData = data;
});
};
});
While this is basic, it captures the main concept. It is advisable to retain a reference to your promise and return it to the caller to prevent redundant HTTP requests if multiple requests are made before the initial request resolves.
By injecting the service into your controller, you can easily retrieve the necessary data. The benefit of this approach is the consistency in calling the method to fetch data. Best of luck with implementing this solution!