[英]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
過濾器,但沒有任何運氣。
通過將項目更改為數組:
$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>
通常,最好使用允許排序,過濾,索引等的數組數據比使用對象更容易
您可以為此創建過濾器
.filter('myFilter', function() {
return function(obj, selected) {
if (!selected) return obj;
return {
value: obj[selected]
}
}
}
這是一個例子
過濾器只適用於數組,正如charlietfl所提到的,你應該把它切換到那個。 如果你不能,你可以使用它,但我強烈建議不要這樣做:
<body ng-controller="MainCtrl">
<ul>
<li ng-repeat="(key, item) in items" data-ng-if="key == selected">
{{item.color}}
</li>
</ul>
</body>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.