如何使用AngularJS ngShow指令仅在元素位于数组中时显示

How to use the AngularJS ngShow directive to show only if an element is in an array?

本文关键字:数组 显示 于数组 ngShow AngularJS 何使用 指令 元素      更新时间:2023-09-26

我的目标是快速地创建一个标记,显示与给定出版物相关的所有作者。

$scope.publications.authors设置为单个值时,一切都正常。当多个值存储在一个数组中时,它们不起作用,如下所示。

我知道AngularJS ngShow指令的条件语句不是用于数组的合适语句,但我似乎不知道实际应该使用什么。

HTML:

<div ng-repeat="person in persons" ng-show="person.firstName == publication.authors">{{person.firstName}}</div>

JS:

$scope.publications = [
{"title": "Research Paper",
 "authors": ["Bill", "George"]};
$scope.persons = [
{"firstName": "Bill",
 "lastName": "Smith"},
{"firstName": "George",
 "lastName": "Jones"},
{"firstName": "Mike",
 "lastName": "Thomas"};

根据publications的数据结构,您需要一个嵌套中继器。您可以使用电流为personpublication的函数来驱动显示器。

<div ng-repeat="publication in publications">{{publication.title}}
    <br/>
    <div ng-repeat="person in people" ng-show="show(person, publication)">{{person.firstName}}</div>
</div>
function ctrl($scope) {
    $scope.publications = [{
        "title": "Research Paper",
            "authors": ["Bill", "George"]
    }];
    $scope.people = [{
        "firstName": "Bill",
            "lastName": "Smith"
    }, {
        "firstName": "George",
            "lastName": "Jones"
    }, {
        "firstName": "Mike",
            "lastName": "Thomas"
    }];
    $scope.show = function (person, publication) {
        return publication.authors.indexOf(person.firstName) >= 0;
    }
}

在控制器中生成函数,该函数可以检查元素是否存在于persons中,并在ng-show中调用它。检查下面的小提琴:

http://jsfiddle.net/HB7LU/323/

我认为最好的方法是在控制器中使用一个方法,而不是尝试迭代DOM中的所有数据。

使用一种方法有多种方法。如果你只想在一行上显示所有作者的名字,你可以有一个方法来获取作者,并返回一个包含所有名字的字符串,并用这个引用这个方法来获取div的内容

{{getAuthors(publication.authors)}}

您还可以有一个方法,返回一个名称数组,并使用类似的ng repeat对其进行迭代