AngularJS 过滤对象 属性

AngularJS Filter Object Property

我的代码正在输出:

使用$scope.selected = '123'的模型我如何编辑它只输出:

这是我的观点:

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

这是我的控制器:

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 的过滤器,但没有成功。

过滤器仅适用于数组,正如 charlietfl 所提到的,您可能应该将其切换为数组。如果你不能,你可以使用它,但我强烈建议不要使用它:

  <body ng-controller="MainCtrl">
     <ul>
      <li ng-repeat="(key, item) in items" data-ng-if="key == selected">
           {{item.color}}     
      </li>
  </ul>
  </body>

通过将项目更改为数组:

 $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

您可以为此创建一个过滤器

.filter('myFilter', function() {
            return function(obj, selected) {
                if (!selected) return obj;

                return {
                    value: obj[selected]
                }
            }
        }

这是一个example