一次响应的多次迭代

时间:2015-05-12 13:22:58

标签: javascript json angularjs single-page-application

我想显示一个包含详细信息的产品列表和产品模型列表,这些列表在详细列表中进行了检查,但我想只用一个获取请求来完成。我的意思是我将获得产品的json,我将在页面中多次使用。

以下是我的产品清单,其中包含详细信息:

<div class="box-content" ng-controller="PostsCtrl" ><div>
<input type="search" ng-model="search"></div>
<table class="table table-striped table-bordered bootstrap-datatable datatable dataTable" id="DataTables_Table_0" aria-describedby="DataTables_Table_0_info">
<thead>
<tr>
<th><tags:label text="productid"/></th>
<th><tags:label text="main.category"/></th>
<th><tags:label text="sub.category"/></th>
<th><tags:label text="brand"/></th>
<th><tags:label text="model"/></th>
<th><tags:label text="sku"/></th>
<th><tags:label text="active"/></th>
<th></th>
</tr>
</thead>
<tbody>
    <tr id="actionresult{{$index + 1}}" ng-repeat="post in posts | filter:search">
    <td>{{post.productid}}</td>
    <td>{{post.subcategory}}</td>
    <td>{{post.subcategoryid}}</td>
    <td>{{post.brand}}</td>
    <td>{{post.model}}</td>
    <td>{{post.brandid}}</td>
    <td><input type="checkbox" ng-model="checked" ng-checked="post.isactive"></td>
    </tr>

模型清单:

<ul ng-controller="PostsCtrl">
  <li ng-repeat="post in posts | filter:checked">{{post.model}}</li>
</ul>

这是我的控制器:

<script>
    var app = angular.module("MyApp", []);

    app.controller("PostsCtrl", function($scope, $http) {
      $http.get('http://localhost/admin.productss/searchwithjson').
        success(function(data, status, headers, config) {
          $scope.posts = data;

        }).
        error(function(data, status, headers, config) {

        });
    });
    </script>

我认为我的行为方式;我做2请求。我也无法列出已检查的模型。

如何修改我的代码?

谢谢。

1 个答案:

答案 0 :(得分:1)

选项1:

使用控制器将两个元素放在同一元素中:

<div class="box-content" ng-controller="PostsCtrl" >

    ...Some other html....

    <table>
        <tr id="actionresult{{$index + 1}}" ng-repeat="post in posts | filter:search">
            <td>{{post.productid}}</td>
            <td>{{post.subcategory}}</td>
            <td>{{post.subcategoryid}}</td>
            <td>{{post.brand}}</td>
            <td>{{post.model}}</td>
            <td>{{post.brandid}}</td>
            <td><input type="checkbox" ng-model="post.checked"></td>
        </tr>
    </table>

    ...Some other html....

    <ul>
        <li ng-repeat="post in posts |  filter:{checked:true}">{{post.model}}</li>
    </ul>

</div>

选项2:

在控制器缓存请求:

app.controller("PostsCtrl", function($rootScope, $scope, $http) {
  $rootScope.cache = $rootScope.cache || {};

  if(!$rootScope.cache.posts){
      $http.get('http://localhost/admin.productss/searchwithjson').
        success(function(data, status, headers, config) {
            $rootScope.cache.posts = $scope.posts = data;
        }).
        error(function(data, status, headers, config) {});
  } else {
      $scope.posts = $rootScope.cache.posts;
  }
});