在AngularJS控制器和服务之间共享资源

时间:2015-11-24 19:03:37

标签: javascript angularjs ajax

我有一个AngularJS服务"人们"通过请求"重"(比如,ajax)资源(JSFiddle)来关联人员列表。

此人员列表是控制器之间的共享。 我想知道这是否是正确的方法,将此列表保存为全局变量。 我这样做是因为不想每次执行ajax请求来恢复初始列表时执行:



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  }];
}
&#13;
input {  width: 40px; }
&#13;
<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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

您可以在服务中缓存AJAX调用的结果,并在第一次调用后返回该结果:

print(s)
print(d)

C:/msds/032-0200.pdf
C:/msds/deluxe/032-0200.pdf
C:/msds/032-0950.pdf
C:/msds/deluxe/032-0950.pdf
C:/msds/040-1300.pdf
C:/msds/deluxe/040-1300.pdf
C:/msds/052-0600.pdf
C:/msds/deluxe/052-0600.pdf