我尝试过滤有条件地使用ng-repeat显示的列表时遇到问题:如果搜索字词以#开头:仅过滤
这是我确切问题的代码:
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>
&#13;
答案 0 :(得分:2)
.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
}
}
});