我从我的数据库中获取了许多具有以下结构的对象:
$scope.user = {
"surname" : "Kowalsky",
"name" : "Jan",
"subject_id" : ["123","678"]
}
我需要显示subject_id
数组中包含“123”的所有用户(姓氏和姓名)。
我尝试在ng-repeat
中执行此操作,但它不起作用。
<div ng-repeat="user in userList | filter: {user.subject_id:'123'}">
<b>Surname: </b>{{user.surname}}
<b>Name: </b>{{user.name}}
</div>
另外,我在控制器中尝试了它,但它也没有用:
$scope.userFilter = $filter('filter')($scope.users.subject_id: '123')[0];
答案 0 :(得分:0)
在模板中使用控制器功能,如下所示:
<div ng-repeat="user in userList | filter: filterUser">
并在控制器中声明函数'filterUser':
$scope.filterUser = function(item) {
if(item.subject_id.indexOf('123') != -1}) {
return true;
}
return false;
}
答案 1 :(得分:0)
试试这个。请记住,您的变量userList是数组。
app = angular.module("App", []);
app.controller("AppController", function($scope){
$scope.userList = [
{
"surname" : "Kowalsky",
"name" : "Jan",
"subject_id" : ["123","678"]
},{
"surname" : "Carlos",
"name" : "Fev",
"subject_id" : ["344","67"]
},{
"surname" : "Joao",
"name" : "Mar",
"subject_id" : ["112","634"]
}
];
}).filter('filterBySubject', function() {
return function(userList, filter) {
var result = [];
for(var i in userList){
if(userList[i].subject_id.indexOf(filter) > -1){
result.push(userList[i]);
break;
}
}
return result;
};
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="App" ng-controller="AppController">
<div ng-repeat="user in userList | filterBySubject:'123'">
<b>Surname: </b>{{user.surname}}
<b>Name: </b>{{user.name}}
</div>
</div>
&#13;
答案 2 :(得分:0)
你可以利用例如lodash可以帮助您处理收藏品 然后你可以在控制器中轻松地预过滤你的收藏
$scope.users = _.filter($scope.users, function(user) {
return _.includes(user.subject_id, '123');
});