简体   繁体   English

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

[英]Share a resource between AngularJS controllers and service

I have a AngularJS service "people" that has associated a people list by requesting a "heavy"(say, ajax) ressource ( JSFiddle ). 我有一个AngularJS服务“人员”,它通过请求“大量”(例如ajax)资源( 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: 我这样做是因为不想每次执行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 }]; } 
 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> 

You could cache the results of the AJAX call in the service and return that after the first call like this: 您可以将AJAX调用的结果缓存在服务中,并在第一次调用后返回,如下所示:

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;
      });
    }
  };
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM