草庐IT

javascript - 从JSON响应中过滤ng-repeat

coder 2024-04-17 原文

我有一个关于在ng-repeat中进行过滤的问题。但这不是一个简单的问题,因为我确实没有需要解决的问题。在这种情况下,我正在寻找不需要大量代码的最佳答案,但是仍然可以完成我想要的技巧。在我的描述中它将变得更加清晰。

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

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

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

  • 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 customer`表。
  • 产品还具有一些链接表。考虑一下价格,税金,尺寸和颜色。 id_product_attribute是可以对应于颜色或大小的attribute_id

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

    使用网络服务
    因此,对于使用Web服务,我使用了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表中提供了以下数据。



    因此,在使用$http.get()response函数时,我能够创建一个用于更新库存的表单。但是现在看看id_product_attribute。此row对应于product_attribute。在这种情况下,为大小或颜色。现在,我想过滤这些结果。在这种情况下,通过使用例如ng-if="id_product_attribute == 0",我能够以仅显示所有带有此id_attribute的方式进行过滤。但我想展示所有这些。所以也有id =“1”,id =“2”等。但是,我想知道的是,有没有一种方法可以以足够的方式做到这一点,而无需为每个id都添加ng-if?由于大约有50种不同的id_attribute,每种对应于一种颜色或大小。因此,有一个函数可以获取每个不同的id并以比使用许多ng-if子句足够的方式对其进行过滤。以下面的完整代码为例。

    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>


    我试图创建以下 View :
  • 产品ID 1:然后是所有尺寸,颜色等
  • 产品ID 2:然后是所有大小,颜色等。



  • 是的,可以编写50个不同的ng-if语句,但是我在问是否有更好,更容易和更充分的方法来做到这一点?

    可以找到一个简单的伪代码here

    一如既往,

    提前致谢!

    最佳答案

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

    因此,您当前拥有一堆“重复的”产品ID(因为查询返回了有关颜色和尺寸的详细信息),但是需要对单个记录进行操作。

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

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

    如果在后端更改SQL太复杂(或在政治上不可行),则可以始终使用javascript来group_:

    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?

    高温超导

    关于javascript - 从JSON响应中过滤ng-repeat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47411695/

    有关javascript - 从JSON响应中过滤ng-repeat的更多相关文章

    1. ruby-on-rails - Rails HTML 请求渲染 JSON - 2

      在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这

    2. ruby-on-rails - 每次我尝试部署时,我都会得到 - (gcloud.preview.app.deploy) 错误响应 : [4] DEADLINE_EXCEEDED - 2

      我是Google云的新手,我正在尝试对其进行首次部署。我的第一个部署是RubyonRails项目。我基本上是在关注thisguideinthegoogleclouddocumentation.唯一的区别是我使用的是我自己的项目,而不是他们提供的“helloworld”项目。这是我的app.yaml文件runtime:customvm:trueentrypoint:bundleexecrackup-p8080-Eproductionconfig.ruresources:cpu:0.5memory_gb:1.3disk_size_gb:10当我转到我的项目目录并运行gcloudprevie

    3. ruby-on-rails - 如何使用 Rack 接收 JSON 对象 - 2

      我有一个非常简单的RubyRack服务器,例如:app=Proc.newdo|env|req=Rack::Request.new(env).paramspreq.inspect[200,{'Content-Type'=>'text/plain'},['Somebody']]endRack::Handler::Thin.run(app,:Port=>4001,:threaded=>true)每当我使用JSON对象向服务器发送POSTHTTP请求时:{"session":{"accountId":String,"callId":String,"from":Object,"headers":

    4. ruby-on-rails - 事件管理员日期过滤器日期格式自定义 - 2

      是否有简单的方法来更改默认ISO格式(yyyy-mm-dd)的ActiveAdmin日期过滤器显示格式? 最佳答案 您可以像这样为日期选择器提供额外的选项,而不是覆盖js:=f.input:my_date,as::datepicker,datepicker_options:{dateFormat:"mm/dd/yy"} 关于ruby-on-rails-事件管理员日期过滤器日期格式自定义,我们在StackOverflow上找到一个类似的问题: https://s

    5. ruby-on-rails - 在 Controller 中干净地处理多个过滤器(参数) - 2

      我有一个名为Post的类,我需要能够适应以下场景:如果用户选择了一个类别,则只显示该类别的帖子如果用户选择了一种类型,则只显示该类型的帖子如果用户选择了一个类别和类型,则只显示该类别中该类型的帖子如果用户没有选择任何内容,则显示所有帖子我想知道我的Controller是否不可避免地会因大量条件语句而显得粗糙...这是我解决此问题的错误方法-有谁知道我如何才能做到这一点?classPostsController 最佳答案 您最好遵循“胖模型,瘦Controller”的惯例,这意味着您应该将这种逻辑放在模型本身中。Post类应该能够报告

    6. ruby - 用 YAML.load 解析 json 安全吗? - 2

      我正在使用ruby2.1.0我有一个json文件。例如:test.json{"item":[{"apple":1},{"banana":2}]}用YAML.load加载这个文件安全吗?YAML.load(File.read('test.json'))我正在尝试加载一个json或yaml格式的文件。 最佳答案 YAML可以加载JSONYAML.load('{"something":"test","other":4}')=>{"something"=>"test","other"=>4}JSON将无法加载YAML。JSON.load("

    7. ruby-on-rails - 如何处理 Grape 中特定操作的过滤器之前? - 2

      我正在我的Rails项目中安装Grape以构建RESTfulAPI。现在一些端点的操作需要身份验证,而另一些则不需要身份验证。例如,我有users端点,看起来像这样:moduleBackendmoduleV1classUsers现在如您所见,除了password/forget之外的所有操作都需要用户登录/验证。创建一个新的端点也没有意义,比如passwords并且只是删除password/forget从逻辑上讲,这个端点应该与用户资源。问题是Grapebefore过滤器没有像except,only这样的选项,我可以在其中说对某些操作应用过滤器。您通常如何干净利落地处理这种情况?

    8. ruby-on-rails - 在 Ruby on Rails 中发送响应之前如何等待多个异步操作完成? - 2

      在我做的一些网络开发中,我有多个操作开始,比如对外部API的GET请求,我希望它们同时开始,因为一个不依赖另一个的结果。我希望事情能够在后台运行。我找到了concurrent-rubylibrary这似乎运作良好。通过将其混合到您创建的类中,该类的方法具有在后台线程上运行的异步版本。这导致我编写如下代码,其中FirstAsyncWorker和SecondAsyncWorker是我编写的类,我在其中混合了Concurrent::Async模块,并编写了一个名为“work”的方法来发送HTTP请求:defindexop1_result=FirstAsyncWorker.new.async.

    9. ruby-on-rails - 使用 javascript 更改数据方法不会更改 ajax 调用用户的什么方法? - 2

      我遇到了一个非常奇怪的问题,我很难解决。在我看来,我有一个与data-remote="true"和data-method="delete"的链接。当我单击该链接时,我可以看到对我的Rails服务器的DELETE请求。返回的JS代码会更改此链接的属性,其中包括href和data-method。再次单击此链接后,我的服务器收到了对新href的请求,但使用的是旧的data-method,即使我已将其从DELETE到POST(它仍然发送一个DELETE请求)。但是,如果我刷新页面,HTML与"new"HTML相同(随返回的JS发生变化),但它实际上发送了正确的请求类型。这就是这个问题令我困惑的

    10. ruby-on-rails - Rails 3 - 过滤器链暂停为 :authentication rendered or redirected - 2

      我仍然收到标题中的“错误”消息,但不知道如何解决。在ApplicationController中,classApplicationController在routes.rb#match'set_activity_account/:id/:value'=>'users#account_activity',:as=>:set_activity_account--thisdoesn'tworkaswell..resources:usersdomemberdoget:action_a,:action_bendcollectiondoget'account_activity'endend和User

    随机推荐