javascript - AngularJS 过滤器对象属性

标签 javascript angularjs angularjs-ng-repeat angularjs-filter

我的代码正在输出:

  • 红色
  • 绿色

使用 $scope.selected = '123' 的模型,我如何将其编辑为仅输出:

  • 红色

这是我的观点:

  <body ng-controller="MainCtrl">
    <ul>
      <li ng-repeat="item in items">
        {{item.color}}
      </li>
    </ul>
  </body>

这是我的 Controller :

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

app.controller('MainCtrl', function($scope) {
  $scope.selected = '123';
  $scope.items = {
    '123': {
      color: 'red',
      quantity: 3
    },
    '456': {
      color: 'blue',
      quantity: 7
    }
  };
});

我尝试使用带有 selected 的过滤器,但没有成功。

最佳答案

通过将项目更改为数组:

 $scope.items =[ 
    {
      id:'123',
      color: 'red',
      quantity: 3
    },
     {
      id:'456',
      color: 'blue',
      quantity: 7
    }
  ];

您可以使用内置的filter,它只适用于数组(也有人谈论对象过滤,不确定它是否存在)

 <li ng-repeat="item in items | filter: {id:selected}">
   {{item.color}}
 </li>

一般来说,使用数组数据比使用对象更容易进行排序、过滤、索引等操作会更好

DEMO

关于javascript - AngularJS 过滤器对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31436359/

相关文章:

javascript - 为什么使用 &lt;input type ="file"/> 时 Angular 绑定(bind)失败?

javascript - Angular 拖放 : Splice not a function on three level

javascript - 我如何在angularjs中的ng-repeat上实现滑动过滤器

javascript - ng-bind-html 的变量名称来自 ng-repeat 但变量在其他地方定义

javascript - 获取 JSON 中的 HTML 以在 React Component 中呈现为 HTML

javascript - 如何全局或从一个点管理 axios 错误

javascript - 使用 Angular js 进行页面重定向的有效方法

javascript - 在 Angularjs 中显示独特的下拉选项

javascript - 使用nodejs tcp服务器接收客户端数据

javascript - 通过在 Google map HTML 中点击获取特定点的纬度和经度