I've got an array of objects loaded into an ng-repeated list. That list is filtered based on the value entered in an input field just above it when a user clicks the 'filter' button. That works fine. However, I also want a select dropdown next to the input to edit the effects of the input filter.
In other words, the way the filter handles the value in the input field should change based on what option is selected in the dropdown next to it.
Here's the code:
HTML:
<div ng-app="programApp" ng-controller="programController">
<label>Name:
<select>
<option>Contains</option>
<option>Equals</option>
<option>Starts with</option>
<option>Ends with</option>
<option>Does not contain</option>
</select>
<input ng-model="nameField" type="text">
</label>
<button ng-click="runFilter()">Filter</button>
<ul>
<li ng-repeat="name in names | filter:filterNameField">{{name.name}}, <i>{{name.age}}</i></li>
</ul>
</div>
Angular:
angular.module('programApp', [
'programApp.controllers',
]);
angular.module('programApp.controllers', [])
.controller('programController', ['$scope', '$filter', '$http',
function($scope, $filter, $http){
$scope.names = [{
'name':'Fred',
'age':'35 years'
},{
'name':'Alberta',
'age':'46 years'
},{
'name':'Francis',
'age':'31 years'
},{
'name':'Sarah',
'age':'12 years'
},{
'name':'Matthew',
'age':'16 years'
},{
'name':'Tracy',
'age':'87 years'
},{
'name':'Jordan',
'age':'35 years'
},{
'name':'Sam',
'age':'26 years'
},{
'name':'Mason',
'age':'38 years'
},{
'name':'Travis',
'age':'11 years'
},{
'name':'Corey',
'age': '86 years'
},{
'name':'Andrew',
'age':'55 years'
},{
'name':'John',
'age':'66 years'
},{
'name':'Jack',
'age':'73 years'
}];
$scope.runFilter = function(){
$scope.filterNameField = $scope.nameField;
};
}]);
So, if Starts with is selected, I want the input to filter by start with, and if equals is selected, only results matching the input exactly should be shown, and so on with the other options. How do I do this?
See equivalent Codepen here.