【问题标题】:AngularJS filter field according to values of an arrayAngularJS根据数组的值过滤字段
【发布时间】:2017-09-05 01:58:43
【问题描述】:

我有一个数组,这个数组包含一些 ID。 我想根据 ID 过滤我的结果。

例如,请参见下面的代码 sn-p。 如何显示“ids”数组中的“StatusId”记录? 根据我的示例,我只想列出:

AAA BBB CCC

<html>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<script>
    angular.module('myApp', []).controller('ctrl', function ($scope) {

        $scope.ids = [{
            "id": 1
        }, {
            "id": 2
        }, {
            "id": 3
        }]

        $scope.records = [
            {
                "Name": "AAA",
                "StatusId": 1
            },
            {
                "Name": "BBB",
                "StatusId": 1
            },
            {
                "Name": "CCC",
                "StatusId": 2
            },
            {
                "Name": "DDD",
                "StatusId": 4
            },
            {
                "Name": "EEE",
                "StatusId": 4
            },
]


    });
</script>


<body>
    <div id="idctrl" ng-app="myApp" ng-controller="ctrl">
        <ul>
            <li ng-repeat="x in records">
                {{ x.Name }}
            </li>
        </ul>
    </div>
</body>

</html>

【问题讨论】:

标签: angularjs arrays angularjs-filter


【解决方案1】:

您可以使用 javascript 的“过滤器”功能:

records = $scope.records.filter((record) => {
    return record.StatusId === 1
});

这将返回一个仅包含 StatusId 为 1 的记录的新数组。您可以使用此更新后的数组来显示您想要的记录。

【讨论】:

  • 对不起,我不清楚。我已将您的函数添加到我的代码中,但结果没有改变。
  • @Grcn 数组有一个过滤函数,它接受一个 function 作为输入,它应该返回 true 或 false。它通过提供的函数传递数组的每个元素,并返回返回 true 的元素的 new 数组。 Read about it here.
  • 仅供参考,如果你正在使用箭头函数,并且函数 just 返回一个值,你可以这样写:(record)=&gt;record.StatusId === 1(或@ 987654324@,因为只有一个参数)
  • 谢谢你们。我明白这一点并解决了我的问题。
猜你喜欢
  • 1970-01-01
  • 2014-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-29
  • 2021-11-03
相关资源
最近更新 更多