javascript - use $http.get in a service/factory to return a collection -


i try use http.get promise in angularjs service, manipulation on obtained collection , return controller...

my question how use $http.get() in service in order obtain , manipulate result before returning controller, in code bellow : 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 = [{'id':88, 'name':"a"}, {'id':89, 'name':"shoutnotbehere"}];     var odds = [];      $http.get("http://www.w3schools.com/angular/customers.php")      .then(function(response) {        = 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 www.w3schools.com/angular/customers.php      <ul>        <li ng-repeat="c in odds">          {{ c.id + ', ' + c.name }}        </li>      </ul>    </div>  </body>

basically modified data inside ajax success call & return data success. returning data ajax success need use promise pattern return out data $http.get. need return object $http.get promise, & inside .then function of $http.get manipulate data.

factory

app.factory('customer', ['$http', function($http) {     var all, odds = [];     var getdata = function() {         return $http.get("http://www.w3schools.com/angular/customers.php")         .then(function(response) {           = response.records;           angular.foreach(all, function(c, i) {             if (i % 2 == 1) {               odds.push(c);             }           });           return odds         });     }     return {         getdata: getdata      }; }]); 

controller

app.controller('customersctrl', ['$scope','customer',function($scope, customer) {     customer.getdata().then(function(response){          $scope.odds = response;     }); }]); 

Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -