ng-repeat中的两个JSON

时间:2017-03-18 19:45:41

标签: javascript angularjs

我有两个JSON。 首先是:

[
    {
        "id": 5,
        "name": "Barsik",
        "age": 3,
        "author": 1
    },
    {
        "id": 6,
        "name": "Gogo",
        "age": 56,
        "author": 2
    },
    {
        "id": 7,
        "name": "Tigger",
        "age": 56,
        "author": 2
    }
]

第二个是:

[
    {
        "id": 1,
        "last_name": "Ivanov",
        "first_name": "Petr"
    },
    {
        "id": 2,
        "last_name": "Bondarev",
        "first_name": "Anton"
    }
]

那么,我怎么能用第二个id来过滤第一个JSON /现在我有这样的代码,它不会过滤任何东西。显然,它应该是第二次重复的一些过滤器,但如何?它应该类似于cat.author == author.id。

<div ng-app="catmodelFrontendApp" ng-controller="MainCtrl">
    <div ng-repeat="author in auth track by author.id">
        <h3>Cats of {{author.first_name}} {{author.last_name}}</h3>
        <div ng-repeat="cat in cats ">{{ cat.name }}</div>
    </div>
</div>

1 个答案:

答案 0 :(得分:1)

通过按属性author.id对其进行过滤,使用此AnuglarJS filter中的runnable demo fiddle。第三个参数true用于比较exect值。

视图

<div ng-controller="MyCtrl">
  <div ng-repeat="author in auth track by author.id">
    <h3>Cats of {{author.first_name}} {{author.last_name}}</h3>
    <div ng-repeat="cat in cats |filter:{'author': author.id}:true"> - {{ cat.name }}</div>
  </div>
</div>

AnuglarJS应用程序

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

myApp.controller('MyCtrl', function ($scope) {
    $scope.cats = [{
            "id": 5,
            "name": "Barsik",
            "age": 3,
            "author": 1
        },
        {
            "id": 6,
            "name": "Gogo",
            "age": 56,
            "author": 2
        },
        {
            "id": 7,
            "name": "Tigger",
            "age": 56,
            "author": 2
        }
    ];

    $scope.auth = [
        {
            "id": 1,
            "last_name": "Ivanov",
            "first_name": "Petr"
        },
        {
            "id": 2,
            "last_name": "Bondarev",
            "first_name": "Anton"
        }
    ];
});