I am trying to utilize a http.get
promise within an angularjs service, perform some manipulation on the retrieved collection, and then pass it back to a controller...
My query is regarding the proper usage of $http.get()
in a service to fetch and modify the result prior to sending it back to the controller. Below is an example code snippet showcasing what I am looking for:
The PEN code
var app = angular.module('myApp', []);
app.controller('customersCtrl', ['$scope','customer',function($scope, customer) {
$scope.odds = customer.odds;
}]);
app.factory('customer', ['$http', function($http) {
var all = [{'Id':88, 'Name':"A"}, {'Id':89, 'Name':"ShoutNotBeHere"}];
var odds = [];
$http.get("http://www.w3schools.com/angular/customers.php")
.then(function(response) {
all = response.records;
});
angular.forEach(all, function(c, i) {
if (i % 2 == 1) {
odds.push(c);
}
});
return {odds: odds};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
Odd ids from www.w3schools.com/angular/customers.php
<ul>
<li ng-repeat="c in odds">
{{ c.Id + ', ' + c.Name }}
</li>
</ul>
</div>
</body>