gpt4 book ai didi

javascript - AngularJS中显示的条件过滤列表

转载 作者:行者123 更新时间:2023-12-02 16:20:49 24 4
gpt4 key购买 nike

我在尝试有条件地过滤使用 ng-repeat 显示的列表时遇到问题:如果搜索词以 # 开头:按书籍过滤/else:仅过滤 通过用户名。

这是我的具体问题的代码笔:

http://codepen.io/prettyGoodPancakes/pen/raoWeB

我的列表如下:

$scope.users = [
{
username: 'clem',
books: [
{ value: 'kafka' },
{ value: 'maupassant' }
]
},
{
username: 'sam',
books: [
{ value: 'Balzac' },
{ value: 'Zola' },
{ value: 'Kafka' }
]
}
];

以下是在此网站上运行的相同代码的片段:

angular.module('ionicApp', ['ionic'])

.controller('MyCtrl', function($scope) {
$scope.users = [{
username: 'clem',
books: [{
value: 'kafka'
}, {
value: 'maupassant'
}]
}, {
username: 'sam',
books: [{
value: 'Balzac'
}, {
value: 'Zola'
}, {
value: 'Kafka'
}]
}];
$scope.$watch(function() {
return $scope.search;
}, function() {
if (scope.search.length > 0) {
if ($rootScope.search[0] === '#') {
// Filter ONLY by books
} else {
// Filter ONLY by username
}
}
}, true);
});
body {
cursor: url('http://ionicframework.com/img/finger.png'), auto;
}
<html ng-app="ionicApp">

<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>Ionic List Directive</title>

<link href="//code.ionicframework.com/nightly/css/ionic.css" rel="stylesheet">
<script src="//code.ionicframework.com/nightly/js/ionic.bundle.js"></script>
</head>

<body ng-controller="MyCtrl">

<ion-header-bar class="bar bar-header item-input-inset">
<label class="item-input-wrapper">
<i class="icon ion-ios7-search placeholder-icon"></i>
<input type="search" placeholder="Search" ng-model="search">
</label>
<button class="button button-clear">
Cancel
</button>
</ion-header-bar>

<ion-content>

<!-- The list directive is great, but be sure to also checkout the collection repeat directive when scrolling through large lists -->

<ion-list>

<ion-item ng-repeat="user in users | filter:search" item="item">
{{user.username}}
<p><span ng-repeat="game in user.books" style="margin-right:5px">{{game.value}}</span>
</p>
</ion-item>

</ion-list>

</ion-content>

</body>

</html>

最佳答案

创建 custom filter :

.filter('PrettyGoodPancakeFilter', function () {
return function(items, filterBy) {
if (filterBy.indexOf('#') === 0) {
return items.filter(function (item) {
return item.username.indexOf(filterBy) > -1;
});
} else {
// filter by books
}
}
});

关于javascript - AngularJS中显示的条件过滤列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29151786/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com