I want the search box to search by name or by city based on the appropriate radio button selected. However, the list it displays will contain name-city pair. I tried ng-if
and ng-true-value
and mg-false-value
, but it won't work. Any suggestions? Here's the code:
<html ng-app="demoApp">
<head>
<script type="text/javascript" src="angular.min.js"></script>
</head>
<body ng-controller="DemoController">
Search: <br/>
<input type="text" ng-model="name"/> {{name}}
<br/><br/>
<input type="radio" ng-model="search.name" ng-value="search.name" name="search" > By Name </input>
<input type="radio" ng-model="search.city" ng-value="search.city" name="search" > By City </input>
<ul>
<li ng-repeat="friend in friends| filter:search.name:friend.name | filter:search.city:friend.city ">{{friend.name}} - {{friend.city}} </li>
</ul>
<script>
var demoApp = angular.module('demoApp',[]);
demoApp.controller('DemoController', function($scope){
$scope.friends = [
{name:'Akshay',city:'Hyderabad'},
{name:'Peeyush',city:'Madras'},
{name:'Aditya',city:'Mumbai'}
];
});
</script>
</body>
</html>
One way is to dynamically create the object required by the filter
filter. Add watches so whenever "By name" is selected, the relevant object will get a property name
, with the value of the text search; whenever "By city" is selected, the object will get a city
property instead.
Simplified code:
(HTML)
<div>
Search: <input type="text" ng-model="search.text" />
<input type="radio" ng-model="search.field" ng-value="'name'" name="sfld">By Name</input>
<input type="radio" ng-model="search.field" ng-value="'city'" name="sfld">By City</input>
<ul>
<li ng-repeat="friend in friends | filter:filterObj">...</li>
</ul>
</div>
(JS)
$scope.$watch("search.field", function(newval) {
if( newval ) {
$scope.filterObj = {};
$scope.filterObj[$scope.search.field] = $scope.search.text;
}
else {
$scope.filterObj = null;
}
});
$scope.$watch("search.text", function(newval) {
if( $scope.search.field ) $scope.filterObj[$scope.search.field] = $scope.search.text;
});
Fiddle: http://jsfiddle.net/97Db6/
Since you mentioned trying to do it with ng-if
, here one simple way that could work:
<input type="radio" ng-model="search" value="name" name="search">By Name
<input type="radio" ng-model="search" value="city" name="search">By City
<ul>
<li ng-if="search == 'name'" ng-repeat="friend in friends | filter: {name : name}">{{friend.name}}, {{friend.city}}</li>
<li ng-if="search == 'city'" ng-repeat="friend in friends | filter: {city : name}">{{friend.name}}, {{friend.city}}</li>
</ul>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.