0

I have a AngularJS service "people" that has associated a people list by requesting a "heavy"(say, ajax) ressource (JSFiddle).

This people list is share between controllers. I wonder if is the proper way to do it, saving this list as a global variable. I do it because don't want to perform each time an ajax request to recuperate the initial list:

var people = [];

var myApp = angular.module('myApp', []);

myApp.controller("infoCtrl", function($scope, person) {
  $scope.people = person.get();
});

myApp.controller("filterCtrl", function($scope, person) {
  $scope.$watch("maxAge", function(newValue) {
    if (newValue) { person.filterPeople(newValue); }
  });
});

myApp.service("person", function() {
  return {
    get: function() {
      people = AjaxGetPeople();
      angular.forEach(people, function(p) {
        p.visible = true;
      });
      return people;
    },
    filterPeople: function(maxAge) {
      angular.forEach(people, function(person) {
        person.visible = person.age <= maxAge;
      });
    }
  };
});

function AjaxGetPeople() {
  return [
    { name: 'Marcel Sapin', age: 26  }, 
    { name: 'Anhel De Niro', age: 42  }, 
    { name: 'Johny Resset', age: 30  }];
}
input {  width: 40px; }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>

<div ng-app="myApp">
  <div ng-controller="filterCtrl" ng-init="maxAge=30">
    People younger than
    <input ng-model="maxAge" type="number" />years:
  </div>
  <hr/>
  <div ng-controller="infoCtrl">
    <div ng-repeat="person in people" ng-show="person.visible">
      {{person.name}}, age {{person.age}}
    </div>
  </div>
</div>
serge
  • 13,940
  • 35
  • 121
  • 205

1 Answers1

2

You could cache the results of the AJAX call in the service and return that after the first call like this:

myApp.service("person", function() {
  return {
    get: function() {
      if (this.people) {
        return this.people; 
      }
      people = AjaxGetPeople();
      angular.forEach(people, function(p) {
        p.visible = true;
      });
      this.people = people;
      return people;
    },
    filterPeople: function(maxAge) {
      angular.forEach(people, function(person) {
        person.visible = person.age <= maxAge;
      });
    }
  };
});
Robert Corey
  • 703
  • 7
  • 19