【问题标题】:AngularJS: Display the first element of the response arrayAngularJS:显示响应数组的第一个元素
【发布时间】:2023-04-16 01:33:01
【问题描述】:

我目前有一个带有两个动态下拉列表的表单(LocationBranch)。 When one of Location values is selected, Branch will automatically populate the corresponding branches with that location.

<select ng-model="formData.location" 
        ng-options="rg as rg.type for rg in region">
    <option value="">Choose Location</option>
</select>

<select ng-model="formData.branches" 
        ng-options="c as c[formData.location.displayName] for c in formData.location.data | orderBy:'branch'">
    <option value="">Choose Branch</option>
</select>

Branch 值取自该控制器:

scope.metro = [
    {"branch": "SM North EDSA", "alias": "northedsa"}, 
    {"branch": "Trinoma", "alias": "trinoma"}, 
    {"branch": "Robinsons Galleria", "alias": "robgalleria"}, 
    // etc...
];

scope.region = [
    { type: 'Metro Manila', data:scope.metro, displayName:'branch', alias:'alias'},
    { type: 'Central Luzon', data:scope.central, displayName:'branch', alias:'alias'},
    { type: 'North Luzon', data:scope.north, displayName:'branch', alias:'alias'},
    // etc...
  ];

现在,在表单内部,Branch 中的每一个 option 更改都会有一个从我的数据库中的表中预先生成的代码(分配给它的每一行),由 ng-repeat 像这样采购:

<div ng-repeat="codes in response">
  <span ng-if="((codes.branch == formData.branches.alias) && (codes.taken == 0))">
  {{codes.code}}
</div>

我的数据库表如下所示:

如果保持原样(每次迭代显示 100 个代码),这将起作用。但是当我使用limitTo:1 之类的过滤器时,我只能获得数据库表中行的第一个索引。我需要的是在 Branch 值的每次翻转时获取 response 数组的第一个元素

为了更清楚的解释,这个 ng-repeat 是通过在我的控制器中使用这个函数来完成的:

http.get("server/fetch.php").success(function(response){
    scope.response = response;
    // shuffleArray(scope.response);
  }).error(function() {
    scope.response = "error in fetching data";
  });

如果我想获取每个数组的第一个元素,我被告知在控制器中执行此操作,但我不确定如何执行此操作。有时间我会发布一个plunker。我现在只需要解决这个问题,因为我有截止日期要在一天结束之前完成。

我希望即使没有笨拙的人,这个问题也很清楚。提前致谢!

【问题讨论】:

  • 你能发布“违规”代码,即没有做你想做的代码
  • &lt;div ng-repeat="codes in response | limitTo:1"&gt; &lt;span ng-if="((codes.branch == formData.branches.alias) &amp;&amp; (codes.taken == 0))"&gt; {{codes.code}} &lt;/div&gt; AngularJS 过滤器只获取我数据库中表的第一个索引。这不是我想要的。我需要在Branch 的每个select 上都有响应数组的第一个元素。
  • | limitTo: 1 将采用response 数组的第一个元素
  • 您需要采用您在ng-if 中使用的条件,并为ng-repeat 创建一个自定义过滤器。然后将该过滤器放入,limit:1 将基于过滤后的数组而不是整个数组
  • @NewDev limitTo: 1 只取第一个索引,而不取第一个元素。我运行它,DZXXK768 是唯一返回的,即使在 optionBranch 更改之后也是如此。

标签: arrays angularjs angularjs-scope angularjs-ng-repeat angularjs-filter


【解决方案1】:

您可以将多个过滤器连接在一起,第一个根据分支过滤,然后限制返回项目的数量:

<div ng-repeat="codes in response | filter: {branch: formData.branches.alias, taken: 0} | limitTo: 1">
   {{codes.code}}
</div>

在这种情况下,可以使用内置的filter 过滤器,因为它允许为多个属性指定谓词以匹配AND 条件。对于任何更复杂的情况,我建议使用谓词函数:

$scope.filterBy = function(a, b){
  return function(item){
    return item.foo === a || item.bar === b;
  }
}

并像这样使用它:

<div ng-repeat="item in items | filter: filterBy('foo', 'bar')">

【讨论】:

  • 这成功了!谢谢! :)