问题描述:

I'm building a job board app using AngularJS to learn about the framework. I got the app to pull data from JSON and added a few filters. While the filters work alright, they don't always display the right results for the search query. Here's the code:

 <h1 class="text-center">Active Jobs</h1>

<div class = "row">

<div class="col-md-4 col-md-offset-6"><input type="text" class="form-control" ng-model = "search" placeholder="Search Jobs"></div>

<div class = "col-md-6 col-md-offset-6">

<label>Sort by:

<select ng-model="jobSearch">

<option value="location" selected>Location</option>

<option value="salary">Salary</option>

<option value="role">Role</option>

</select>

</label>

<label class="formgroup">

<input type="radio" ng-model="order" name ="order" checked> ascending

</label>

<label class="formgroup">

<input type="radio" ng-model="order" name ="order" value = "reverse"> descending

</label>

</div>

</div>

</div>

<div class="row" ng-repeat="job in jobs | filter:search | orderBy: jobSearch:order">

<div class="col-md-6">

<h2><a href = "#/jobs/{{ jobs.indexOf(job) }}">{{ job.designation }}</a></h2>

<p>{{ job.location }}</p>

<p>{{ job.role }}</p>

<p>{{ job.salary | currency }}</p>

</div>

</div>

</div>

I have created jobs in locations like Austin, San Francisco, Hertfordshire etc. When I start typing, say, "He" or "Her", in addition to the Hertfordshire listing, few other listings show up as well. On closer examination, I found that words with these letters appear in the description of those listings. The same happens when I search using role (remote, full time, part time) as well. How do I ensure that queries are performed only on the attribute selected in the drop down and not the entire listing?

网友答案:

search in

<div class="row" ng-repeat="job in jobs | filter:search | orderBy: jobSearch:order">

is bound to a string in your input. When using a String in a filter, all objects in array with string properties containing the search value will be returned.

If you want to search only on location, change the ng-model of your input to :

<input type="text" class="form-control" ng-model = "search.location" placeholder="Search Jobs">

Edit

It should be easier to use a function in your controller

$scope.search(value) {
     return value[$scope.jobSearch] == $scope.searchTerm;
}

In your html, you bind the input search to the searchTerm :

 <input type="text" class="form-control" ng-model = "searchTerm" placeholder="Search Jobs">

And your filter to the search function :

 <div class="row" ng-repeat="job in jobs | filter:search() | orderBy: jobSearch:order">

Hope that help

网友答案:
<div class="row" ng-repeat="job in jobs | filter:{jobSearch: search} | orderBy: jobSearch:order">

check this one

相关阅读:
Top