I'm having trouble using an ng-model in a filter function. The input is currently named "search.anything". I can't change the name as it will effect other filters.
I want to use it as a parameter in a filter function. Is there any other way I can enter the value? $scope.search.anything is definitely wrong.
$scope.myFilter = function(course) {
var isMatch = false;
if ($scope.search.anything) {
var parts = $scope.search.anything.split(' ');
parts.forEach(function(part) {
if (new RegExp(part).test(course.keywords)) {
isMatch = true;
}
});
} else {
isMatch = true;
}
return isMatch;
};
Any help would be appreciated.
Demo:
var app = angular.module('myApp', []); app.controller('AppCtrl', function($scope) { $scope.message = "Hello World;"; });
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script> <section ng-app="myApp"> <div ng-controller="AppCtrl"> <h1>Message: {{message}}</h1> </div> </section>
You could use an md-input-container
( ref ) to input the filter value (here I use an input
, but you could use an md-select
or any other input method. In the ng-repeat
you could use a custom filter ( filter: functionFilter
, ref ).
To handle the "." inside the property name you could save it in a variable ctrl.searchKey = "search.anything";
and any time you want to acces it in JS ctrl[ctrl.searchKey] = "value1";
and in HTML you could also use a string literal "ctrl['search.anything']"
.
If you change the "Filter value" to "value2" or "value3" it will filter the ng-repeat
.
Here is a code snippet example. Hope this helps.
var app = angular.module('myApp', []); app.controller('AppCtrl', function($scope) { const ctrl = this; ctrl.data = [{ value: "value1" }, { value: "value2" }, { value: "value3" }]; ctrl.searchKey = "search.anything"; ctrl[ctrl.searchKey] = "value1"; ctrl.myFilter = input => input.value === ctrl[ctrl.searchKey]; });
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script> <section ng-app="myApp"> <div ng-controller="AppCtrl as ctrl"> <md-input-container> <label>Filter value</label> <input ng-model="ctrl['search.anything']"> </md-input-container> <div ng-repeat="entity in ctrl.data | filter: ctrl.myFilter"> Value filtered {{ entity.value }}</div> </div> </section>
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.