AngularJS Factory在每次点击时加载数据

时间:2014-04-16 17:27:15

标签: javascript angularjs angularjs-scope angular-ui

Plunker

有很多文件,所以也许你们Angular爱好者会理解我的解释,或者能够跟随我上面提供的那些人。

我正在创建一个模块化网页的演示。甚至页面的主要内容也将在另一个模板文件中。在主要内容视图中,有一个链接表,该链接打开一个angular-bootstrap模式(另一个模板/控制器),显示所点击对象的附加信息。

我发现每次点击链接时,工厂都在检索源数据。对于小的东西,它是不明显的,但如果你对大型数据集执行AJAX请求,或者将XML转换为JSON,这可能需要一段时间。我不确定这是否是路由的结果,或者它是否是我试图完成的不良实现,但我想:

  1. 明白为什么会发生这种情况
  2. 检索初始数据一次并在控制器之间共享

  3. data.json

    [
      {"firstName":"John",
       "lastName":"Denohn",
       "profession":"Student",
       "age":10
      },
      {"firstName":"Mark",
       "lastName":"Fatzigio",
       "profession":"Doctor",
       "age":20
      },
      {"firstName":"Jennifer",
       "lastName":"Cooler",
       "profession":null,
       "age":30
      },
      {"firstName":"Kimberly",
       "lastName":"Branch",
       "profession":"Teacher",
       "age":40
      }
    ]
    

    的index.html

    <!DOCTYPE html>
    <html lang="en" data-ng-app="myApp">
      <head>
    
        <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet">
        <link href="myApp.css" rel="stylesheet">
    
        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.js"></script>
        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>
        <script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.10.0.js"></script>
    
      </head>
    
      <body>
        <div data-ng-view="" data-ng-cloak ></div>
    
        <script src="myApp.js"></script>
        <script src="myAppModels.js"></script>
        <script src="myAppControllers.js"></script>
      </body>
    
    </html>
    

    template_initialPageView.html

    <div class="page-container" data-ng-cloak>
    
      <!-- Table Content -->
      <table class="table" data-ng-cloak>
        <thead>
          <tr><th colspan="{{keysToShow.length}}"><h1>People</h1></th></tr>
          <tr><th data-ng-repeat="header in keysToShow">{{ header.displayName }}</th></tr>
        </thead>
        <tbody>
          <tr data-ng-repeat="person in people | orderBy:orderProp">
            <td><a href="#{{[person.firstName, person.lastName].join('_')}}" 
                  data-ng-click="showModal(person)"
                  >{{ [person.firstName, person.lastName].join(' ') }}</a></td>
            <td>{{ person.profession }}</td>
          </tr>
        </tbody>
      </table>
    
    </div>
    

    template_modalContentView.html

    <div class="modal-header">
      <button type="button" class="close" data-ng-click="cancelModal()">&times;</button>
      <h3 class="modal-title" id="myModalLabel">Person Info</h3>
    </div>
    <div class="modal-body">
      <tabset>
        <tab heading="Age">
          <h4>Name</h4>
          <p>{{ person.firstName + ' ' + person.lastName }}</p>
    
          <h4>Age</h4>
          <pre>{{ person.age }}</pre>
        </tab>
        <tab heading="Profession">
          <h4>Name</h4>
          <p>{{ person.firstName + ' ' + person.lastName }}</p>
    
          <h4>Profession</h4>
          <pre>{{ person.profession }}</pre>
        </tab>
      </tabset>
    </div>
    <div class="modal-footer">
      <button class="btn btn-primary" data-ng-click="closeModal()">Close</button>
    </div>
    

    myApp.js

    var myApp = angular.module('myApp', ['ui.bootstrap', 'ngRoute']);
    
    /* Routes */
    myApp.config(function($routeProvider) {
      $routeProvider
        .when('/home', {
          templateUrl: 'template_initialPageView.html',
          controller: 'PageViewController',
          controllerAs: 'page'
        })
        .otherwise({
          redirectTo: '/home'
        });
    });
    

    myAppControllers.js

    var myAppControllers = {};
    
    // Define: Page View Controller
    myAppControllers.PageViewController = function ($scope, $modal, modelFactory) {
    
      init();
    
      function init(){
        $scope.orderProp  = '';
        $scope.keysToShow = [{'displayName':'Fullname'},{'displayName':'Profession'}];
        modelFactory.getPeople().success(function(data){
          $scope.people = data;
        });
      }
    
      $scope.showModal = function(person) {
        console.log('person clicked', person);
        $scope.person = person;
    
        var modalInstance = $modal.open({
          controller: 'ModalController',
          controllerAs: 'modal',
          templateUrl: 'template_modalContentView.html',
          resolve: {
            person: function(){
              return $scope.person;
            }
          }
        });
    
      };
    
    };
    
    
    // Define: Modal Controller
    myAppControllers.ModalController = function ($scope, $modalInstance, person) {
      init();
    
      function init(){
        $scope.person = person;
      }
    
      $scope.cancelModal = function (){
        $modalInstance.dismiss('cancel');
      };
    
      $scope.closeModal = function () {
        $modalInstance.close();
      };
    
    };
    
    
    // Add controlers to the module
    myApp.controller(myAppControllers);
    

    myAppModels.js

    myApp.factory('modelFactory', function($http){
      var factory = {};
    
      factory.getPeople = function (){
        return $http.get('data.json');
      };
    
      return factory;
    
    });
    

1 个答案:

答案 0 :(得分:1)

你可以尝试这个,它最初返回一个空数组,它将在$http.get() returns时填充,每次调用它时它都会重新使用数组:

myApp.factory('modelFactory', function($http){
  var factory = {};

  factory.getPeople = function () {
    if (typeof(factory.people) == "undefined") {
      factory.people = [];
      $http.get('data.json').success(function(result) {
        var i = 0;
        for (i = 0; i < result.length; i++) {
          factory.people.push(result[i]);
        }
      });
    }
    return factory.people;
  };

  return factory;

});

并且不要忘记更改您的作业以接受数组并使用它:

$scope.people = modelFactory.getPeople();

(PLUNKR)