【问题标题】:Filter Embedded Json element from a Collection using AngularJS HTML使用 AngularJS HTML 从集合中过滤嵌入的 Json 元素
【发布时间】:2016-10-20 15:22:09
【问题描述】:

我有一个 JSON 集合,我希望使用没有 . 用户名

我的 JSON 集合:

{ "user" : [
    {
        "Name" : "B. Balamanigandan",
        "Email": [
            {
                "Id": "bala@gmail.com",
                "IsPreffered": true
            },
            {
                "Id": "mani@gmail.com",
                "IsPreffered": false
            }
    ]}
]};

HTML 源代码:

<div>
    <h3>Employee Details:</h3>
    <span> {{collection.user.Name}} </span>
    <span> {{collection.user.Email.Id}} </span>
</div>

集合user仅包含一个文档。所以,我没有使用 ng-repeat。 user 是集合而不是文档。我还需要一张支票。如果不止一封电子邮件有“IsPreferred == true”,那么我会选择最后一封。请帮助我。

请使用 HTML 级别而不是 JavaScript 级别来过滤条件。请帮助我。

【问题讨论】:

  • 你的 ngRepeat 在哪里?
  • @dfsq 集合 user 仅包含一个文档。所以,我没有使用 ng-repeat。 user 是一个集合而不是一个文档。请帮助我。

标签: javascript html angularjs json angular-filters


【解决方案1】:

而不是这个:

<div>
    <h3>Employee Details:</h3>
    <span> {{collection.user.Name}} </span>
    <span> {{collection.user.Email.Id}} </span>
</div>

你必须这样做:

<div>
    <h3>Employee Details:</h3>
    <span> {{collection.user[0].Name}} </span>

    <span ng-repeat="email in collection.user[0].email| filter: {IsPreffered : 'true'}"> {{email.Id}} </span>
</div>

您必须使用数组语法,因为虽然只有 1 个用户对象,但它在 json 中被结构化为一个数组(注意 [ ] ,与电子邮件相同)。

这是一个小提琴:http://jsfiddle.net/Lvc0u55v/5593/

更新:为了只显示最后一封正确的电子邮件,请使用 ng-if:

<span ng-repeat="email in collection.user[0].Email| filter: {IsPreffered : true} " ng-if="$last"> {{email.Id}}</span>

这是更新后的小提琴: http://jsfiddle.net/Lvc0u55v/5594/

【讨论】:

  • 谢谢,但我还需要一张支票。如果不止一封电子邮件有 `IsPreferred == true',那么我会选择最后一封。请帮助我。
  • 请更新您的问题详细信息,以提及这一点。
  • 我需要您提供另一种解决方案。我发布了一个新问题stackoverflow.com/questions/37905191/…请帮助我。
【解决方案2】:

一种方法是在用户电子邮件数组上使用ngRepeatfilter,以仅获取那些位于"IsPreffered": true 的电子邮件。过滤器将 Emails 数组中的每个对象与过滤器对象 (filterEmail) 进行比较。此过滤器对象在控制器中定义 - 这样您就可以根据需要进行更改,甚至可以动态设置它。

var app = angular.module('app', []);
app.controller('ctrl', function($scope) {
  $scope.collection = {
    "user": {
      "Name": "B. Balamanigandan",
      "Email": [{
        "Id": "bala@gmail.com",
        "IsPreffered": true
      }, {
        "Id": "mani@gmail.com",
        "IsPreffered": false
      }]
    }
  };

  $scope.filterEmail = {
    "IsPreffered": true
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>


<body ng-app="app" ng-controller="ctrl">
  <div>
    <h3>Employee Details:</h3>
    <span> {{collection.user.Name}} </span>
    <span ng-repeat="email in collection.user.Email | filter : filterEmail "> 
      {{email.Id}} 
    </span>
  </div>
</body>

注意:据我了解,将user 作为对象内的数组没有多大意义(在我的示例中,我删除了内部数组)。如果您坚持保留此数据模式,则需要将 collection.user 的每个引用更改为 collection.user[0]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    • 1970-01-01
    • 2019-06-26
    • 1970-01-01
    • 2023-03-10
    相关资源
    最近更新 更多