【问题标题】:How to get distinct values from JSON based on Foriegn Key using angularJS如何使用angularJS基于外键从JSON中获取不同的值
【发布时间】:2016-05-26 05:56:18
【问题描述】:

我有两个 JSON 数组,$scope.data 有主要细节,我想在 UI 中显示,因为 cInstId 是来自 JSON $scope.color 的 foreign key

两个 JSON 数组是

$scope.data = [
    {
        "id": 1,
        "cTitle": "One",
        "cInstId": 1
    },
    {
        "id": 2,
        "cTitle": "Two",
        "cInstId": 2
    },
    {
        "id": 3,
        "cTitle": "Three",
        "cInstId": 3
    },
    {
        "id": 4,
        "cTitle": "Four",
        "cInstId": 4
    },
    {
        "id": 5,
        "cTitle": "Five",
        "cInstId": 4
    }
];

$scope.color = [
    {
        "cInstId": 1,
        "cInstTitle": "Blue"
    },
    {
        "cInstId": 2,
        "cInstTitle": "Green"
    },
    {
        "cInstId": 3,
        "cInstTitle": "Red"
    },
    {
        "cInstId": 4,
        "cInstTitle": "Orange"
    },
    {
        "cInstId": 5,
        "cInstTitle": "Violet"
    }
];

我的预期输出应该和图片一样

<div ng-repeat="members in data">
    <!-- How to Show it in the UI -->
</div>

注意:不要在 控制器。

【问题讨论】:

  • 您尝试过什么吗?向我们展示代码。
  • @ParthaSarathiGhosh 请帮助我...

标签: angularjs json foreign-keys angularjs-ng-repeat angularjs-filter


【解决方案1】:

您可以在此处使用自定义过滤器。

angular.module('ModuleName').filter('color', function($filter) {
  return function(id, colorArray) {
    return $filter('filter')(colorArray,{'cInstId': id})[0].cInstTitle;
  };
});

按如下方式使用此过滤器:

<div ng-repeat="members in data">
    <!-- How to Show it in the UI -->
    <span>{{member.cInstId | color:color}}</span><!--Second color is your scope var -->
</div>

注意:我用过thisthis

但如果您可以创建颜色服务并使用该服务并直接使用数组,那就更好了。

【讨论】:

  • 看看我的自定义过滤器,它正在校准角度过滤器并传递您的颜色数组。它还会传递您提供的 id 以在此处找到确切的颜色。
  • 可以在 ColorService 中使用 $scope.color 而不是手动输入 JSON ???
  • YES 那么您需要将数组作为过滤器输入传递。如下~ {{member.cInstId |颜色:collorArray}}~.
猜你喜欢
  • 1970-01-01
  • 2017-07-19
  • 1970-01-01
  • 2017-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多