从JSON响应中过滤ng-repeat

时间:2017-11-21 11:12:24

标签: javascript php angularjs json web-services

我有一个关于在ng-repeat中过滤的问题。但这不是一个简单的问题,因为我真的没有需要解决方案的问题。在这种情况下,我正在寻找最好的答案,不需要很多代码,但仍然可以解决我想要的方法。在我的描述中会更清楚。

简短介绍:
所以我目前正在开发一个购物应用程序。购物应用程序通过Web服务API与现有的PrestaShop网上商店建立连接。 PrestaShop的休息API。因此,在创建客户部分,产品部分和购物车系统后,我希望能够更新应用程序中每个产品的“库存量”。很多人会告诉我:这很简单,只需创建一个包含来自数据库的ng-repeat响应数据的表单,以及更新库存的可能性,例如按钮ng-click事件。

嗯,我已经做到了,但现在是棘手的部分,并解释我将提供一些不太重要的例子,以使其更清楚我所要求的:

prestashop数据库
prestashop数据库是一个包含250多个表的数据库。这些表中有通过id和属性id的各种连接。一些简单的例子是:

  1. customer表有id_address行,连接到address表。在此表中,所有“客户address info is placed. So far, let's say updating a customer I've created a combination of update the客户table with the customer_id but also update the地址table where the address_id is equal to the id_address from the selected客户within the客户`table。

  2. 产品还有一些链接表。考虑价格,税收,尺寸和颜色。 id_product_attributeattribute_id,可以与颜色或尺寸相对应。

  3. 如上所述,prestashop数据库结构非常详细,仅限于使用各种过滤器来显示所需数据。

    使用网络服务
    因此,对于使用网络服务,我使用angularJSjavascriptphpJSON的组合。 JSON是实际数据。通过使用$http.get(url, options)我能够从数据库中获取数据。然后显示我正在使用response的数据。示例如下所示:

    $http.get('config/get/getCustomers.php', { cache: true }).then(function (response) {
        $scope.customers = response.data.customers.customer
    });
    

    使用$scope.customers = response.data.customers.customer为我提供了显示客户数据的选项,例如使用ng-repeat,如下例所示

        $http.get('config/get/getCustomers.php', { cache: true }).then(function (response) {
            $scope.customers = response.data.customers.customer
        });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div class="row listrow" ng-repeat="customer in customers | orderBy: customer.id">
    		<div class="col-lg-8">
    			<p class="customer" ng-bind="customer.id + ' ' + customer.firstname + ' ' + customer.lastname">
          </p>
    		</div>
    </div>

    在这种情况下,由于没有数据库连接,响应将为空。要在此处创建完整的测试示例,您可以在JSON表中使用一些customers数据。

    {"customers":{"customer":[{"id":"1","id_default_group":"0","id_lang":"0","newsletter_date_add":"0000-00-00 00:00:00","ip_registration_newsletter":{},"last_passwd_gen":"2017-10-30 09:27:03","secure_key":{},"deleted":"0","passwd":"$2y$10$eZvPTD9bkxwSfWN7qovrmee\/Den2TqZ5a6YjcGC\/lha3oU59MCjOO","lastname":"TestStefans","firstname":"John","email":"pub@prestashop.com","id_gender":"0","birthday":"0000-00-00","newsletter":"0","optin":"0","website":{},"company":{},"siret":{},"ape":{},"outstanding_allow_amount":"0.000000","show_public_prices":"0","id_risk":"0","max_payment_days":"0","active":"1","note":{},"is_guest":"0","id_shop":"1","id_shop_group":"1","date_add":"2017-04-26 14:01:31","date_upd":"2017-10-27 15:56:54","reset_password_token":{},"reset_password_validity":"0000-00-00 00:00:00","associations":{"groups":{"@attributes":{"nodeType":"group","api":"groups"},"group":{"id":"3"}}}},{"id":"2","id_default_group":"0","id_lang":"1","newsletter_date_add":"0000-00-00 00:00:00","ip_registration_newsletter":{},"last_passwd_gen":"2017-10-27 15:56:55","secure_key":{},"deleted":"0","passwd":"$2y$10$C8M6TIuzmZjP9kh06Hai8.XyuNG9WcSi9L34oXqAuidsJkoYog4WW","lastname":"Demoers","firstname":"Demoers","email":"demo@sdwebdesign.nl","id_gender":"0","birthday":"0000-00-00","newsletter":"0","optin":"0","website":{},"company":{},"siret":{},"ape":{},"outstanding_allow_amount":"0.000000","show_public_prices":"0","id_risk":"0","max_payment_days":"0","active":"1","note":{},"is_guest":"0","id_shop":"1","id_shop_group":"1","date_add":"2017-04-26 14:01:33","date_upd":"2017-10-27 15:56:55","reset_password_token":{},"reset_password_validity":"0000-00-00 00:00:00","associations":{"groups":{"@attributes":{"nodeType":"group","api":"groups"},"group":{"id":"3"}}}}]}}
    

    所以这里有这些信息是我的问题:

    在处理应用程序时,stock_availables表中提供了以下数据。

    The stock_availables table

    因此,在使用$http.get()response函数时,我能够创建一个用于更新股票的表单。但现在看一下id_product_attribute。此row对应于product_attribute。在这种情况下,大小或颜色。现在我想过滤这些结果。在这种情况下,通过使用例如ng-if="id_product_attribute == 0",我能够以仅显示此id_attribute的所有内容的方式进行过滤。但我想展示所有这些。所以id =“1”,id =“2”等等。但是我想知道,有没有办法以足够的方式做到这一点,每个都不需要ng-if ID?由于大约有50种不同的id_attribute,每种ng-if都对应一种颜色或大小。那么是否有一个函数可以获得每个不同的id并以足够的方式过滤使用许多myApp.controller('ProductsController', function($scope, $http){ $http.get('config/get/getProducts.php', {cache: true}).then(function(response){ $scope.products = response.data.products.product }); // Stock check + view $http.get('config/get/getStock.php', {cache: true}).then(function (response) { $scope.stock_availables = response.data.stock_availables.stock_available }); // Update Stock $scope.updateStock = function(stock_available) { var stock_id = stock_available.id; var product_id = stock_available.id_product; var stock_quantity = stock_available.quantity; console.log(stock_id + product_id + stock_quantity); // Post to the database // }; });子句。请查看以下完整代码作为示例。

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div class="row listrow">
    		<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
    			<ng-form name="stock">
    				<div ng-repeat="stock_available in stock_availables">
    					<div class="row full-width padding-tb-15" ng-if="stock_available.id_product == product.id  && stock_available.id_product_attribute == 0" ng-repeat="product in products">
    						<div class="col-lg-12 form-stock-group hidden">
    							<input title="id" type="text" name="stockId" class="form-control" aria-describedby="" ng-value="stock_available.id">
    						</div>
    						<div class="col-lg-4">
    							<h5 ng-bind="product.name.language"></h5>
    						</div>
    						<div class="col-lg-3">
    							<h5 ng-bind="product.ean13"></h5>
    						</div>
    						<div class="col-lg-2">
    							<h5 ng-bind="product.reference"></h5>
    						</div>
    						<div ng-if="stock_available.id_product == product.id && stock_available.id_product_attribute == 0" ng-repeat="stock_available in stock_availables" class="col-lg-1 text-center">
    							<input title="stock_id" type="text" name="stock_id" class="form-control hidden" aria-describedby=""  ng-model="stock_available.id" ng-value="stock_available.id">
    							<input title="stock_id_product" type="text" name="stock_id_product" class="form-control hidden" aria-describedby="" ng-model="stock_available.id_product" ng-value="stock_available.id_product">
    							<h5 title="quantity" name="stockQuantity" aria-describedby="" ng-model="stock_available.quantity" ng-bind="stock_available.quantity"></h5>
    						</div>
    						<div ng-if="stock_available.id_product == product.id && stock_available.id_product_attribute == 0" ng-repeat="stock_available in stock_availables" class="col-lg-1 text-center">
    							<input title="updateStockAmount" class="form-control form-control-stock" type="number">
    						</div>
    						<div class="col-lg-1 text-center">
    							<a ng-click="printStockLabel()">
    								<i class="fa fa-print" aria-hidden="true"></i>
    							</a>
    						</div>
    					</div>
    				</div>
    			</ng-form>
    		</div>
    	</div>
    ng-if

    我尝试创建以下视图:

    1. 产品ID 1:然后是所有尺寸,颜色等
    2. 产品ID 2:然后是所有尺寸,颜色等
    3. Simple design

      是的,可以编写50个不同的{{1}}语句,但我在问是否有更好,更简单,更充分的方法来执行此操作?

      可以找到虚拟代码的简单构建here

      一如既往,

      提前致谢!

5 个答案:

答案 0 :(得分:1)

您是否考虑过使用数据库并让数据库为此屏幕生成特定查询,该查询将所有产品组合在一起??

所以你目前有一堆“重复”的产品ID(因为查询会返回颜色和大小的详细信息),但是需要对单个记录进行操作。

您可以使用GROUP BY SQL查询语句在后端执行此操作。

如果更多程序正在使用该端点,只需将您的端点“仅用于此屏幕”并应用必要的更改。

如果更改后端的SQL太复杂(或政治上不可靠),您可以使用javascript始终group_by:

https://www.consolelog.io/group-by-in-javascript

group_by将数据集和列(即)作为输入。

给出如下数据集:

c1 c2 c3
1  10 10
1  11 10
3  12 20

// this operation:
groups = group_by(dataset, "c1")

//returns this:

groups:

group 1 (2 elements)
    c2  c3
    10  10
    11  10
group 3 (1 element)
    c2  c3
    12  10

这意味着您可以将分组的数据集反馈回网格程序,因此它可以将组显示为组,将项目显示为项目,通过首先遍历组,然后再遍历项目。

有很多方法可以实现group_by,如下所示:

What is the most efficient method to groupby on a javascript array of objects?

HTH

答案 1 :(得分:1)

也许您应该问问自己,您的应用程序的哪个部分负责对这些属性进行排序。这可能会为您带来更明显的解决方案。 如果责任转到API,那么您的请求或API应该为您的WebApp返回一个可立即使用的JSON。 如果责任转到前端WebApp,请在js代码或模板中执行。

我的猜测是你的API应该这样做,在这种情况下我可能不是最顾问的。 但是如果您决定在WebApp中执行此操作,我绝对认为您不应该使用ngIf来执行此操作,而是在JS中构建Pure Functions以构建一个或多个数组,您可以使用它们而不是太多功能名称模板中的代码。

例如,你可以.map()你的响应并返回一个很好的可迭代对象,和/或用.concat()或其他东西链接它。如果您需要构建此类函数的想法,请检查示例http://reactivex.io/learnrx/

答案 2 :(得分:1)

通过阅读您的问题,我建议您不要使用ng-if n次,而是可以在控制器内部进行过滤,例如

  $scope.getFilteredList = function() {
     return $scope.stock_availables.filter(function(stock) {
       return stock.id_product === $scope.selectedID;   // $scope.selectedID will be the id to be filter, in your example '0'
     });
  }

您的ng-repeat将更改为

<div ng-repeat="stock_available in getFilteredList">

答案 3 :(得分:0)

我认为最好让DB为你订购。 但您可以尝试使用AngularJS orderByfilter

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

module.controller('MyController', function($scope){

  $scope.list = [
  { 'id': 0, 'count': 10 },
  { 'id': 1, 'count': 9 },
  { 'id': 2, 'count': 8 }];

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="MyApp">
  <div ng-controller="MyController">

    <div ng-repeat="member in list | orderBy:'-count'">
      {{member.id}}
    </div>
    <hr>
    <div ng-repeat="member in list | filter: {id:0}">
      {{member.id}}
    </div>
    <hr>
    <div ng-repeat="member in list | orderBy: '-count' | filter: {id : '!0'}">
      {{member.id}}
    </div>
  </div>
</div>

答案 4 :(得分:0)

我还建议使用db查询来提供元素的排序。但是,我们始终无法更改后端或其运行方式。

SO ..

我建议在设置$scope.customers

之前使用排序功能转换您的回复数据
$http.get('config/get/getCustomers.php', { cache: true }).then(function (response) {
        var temp = response.data.customers.customer;
        temp.sort(fucntion (item1, item2) {
            if (item1.product === item2.product) {
                if (item1.size === item2.size) {
                    return item1.color > item2.color;
                }
                return item1.size > item2.size;
            }
            return item1.product > item2.product;
        }
        $scope.customers = temp
 });
相关问题