我在AngularJS中有对象:
genres = [{
label: "Trance",
genre: "8",
position: 8
}, {
label: "House",
genre: "2",
position: 8
}]
如何genre
按ng-click
过滤此数组?
例如ng-click="filterByGenre(2)"
。
它应该只返回一个元素:
{
label: "House",
genre: "2",
position: 8
}
答案 0 :(得分:3)
这是您尝试实现的简单工作Fiddle。它会按属性genre
过滤您的对象,您可以在文本字段中搜索Id
。例如8
。
查看过滤器声明filter:{genre:searchGenre}
,其中包含要过滤的属性名称genre
和模型输入searchGenre
。有关详细信息,请查看AngularJS Documentation of filter。
<div ng-controller="MyCtrl">
<h1>Filter items</h1>
<input type="text" ng-model="searchGenre">
<h2>Genres</h2>
<div ng-repeat="genre in genres | filter:{genre:searchGenre}">
{{genre.label}}
</div>
</div>
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.genres = [{
label: "Trance",
genre: "8",
position: 8
}, {
label: "House",
genre: "2",
position: 8
}];
}
<div ng-controller="MyCtrl">
<div>Filter items</div>
<input type="text" ng-model="searchGenre">
<div>Genres</div>
<div ng-repeat="genre in filtered">
{{genre.label}}
</div>
</div>
var myApp = angular.module('myApp',[]);
function MyCtrl($scope, filterFilter) {
$scope.genres = [{
label: "Trance",
genre: "8",
position: 8
}, {
label: "House",
genre: "2",
position: 8
}];
//init search phrase
$scope.searchGenre = '';
//init filtered scope
$scope.filtered = [];
/**
* Watch keyword change
*/
$scope.$watch('searchGenre', function(term) {
$scope.filtered = filterFilter($scope.genres, {'genre': term});
});
}
答案 1 :(得分:1)
试试这样。
var app = angular.module('app', []);
app.controller('myController', function($scope){
$scope.genres = [
{
label: "Trance",
genre: "8",
position: 8
},
{
label: "House",
genre: "2",
position: 8
}
];
$scope.setGenreFilter = function(genre){
$scope.genreFilter = genre;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="myController">
<div>Filter items</div>
<span ng-repeat="genre in genres" ng-click="setGenreFilter(genre.genre)">{{genre.genre}}, </span>
<div>****************GENRE**********************</div>
<div ng-repeat="item in genres | filter:{genre:genreFilter}">
{{item.label}}
</div>
</div>
答案 2 :(得分:-1)
您可以使用filter功能
genres.filter(function(item){
return item.genre == '2';
});
或者你可以用旧的for循环方式
var filteredData = [];
for(var i=0;i<genres.length;i++){
if(genres[i].genre == '2'){
filteredData.push(genres[i]);
}
}