custom filter with AngularJS

0

Personally, I have the following problem, I have a list of names:

$scope.names=["Max", "Tom", "Ralf", "Jerry", "Snow", "Carl"];

I made a normal filter for the input search

<ul>
  <li ng-repeat="name in names | filter: search">{{name}}</li>
</ul>
</div>
<div>
<input type="search" ng-model="search">
</div>

However, I want to create a custom filter to display only the names related to 1st letter entered in the input search, in this case, type the letter "R" and the result is just "Ralf" instead of searching the "R" in all the lyrics, which results in "Ralph" and "Jerry".

I thought of using an angular.forEach to scroll through the names but did not get the result I wanted, if it helps, follow the codepen to make it easier:

link

    
asked by anonymous 18.09.2014 / 20:25

2 answers

1

Well, I found a solution like I wanted it, I just did not understand the part of regex.test but I think the solution might serve other people with doubts.

var List = function($scope){
 $scope.names=["Tax", "Tom", "Ralf", "Jerry", "Snow", "Carl"];

  function escRegExp(string){
   return string.replace(/([.*+?^=!:${}()|\[\]\/\])/g);
    }

  $scope.filterSearch = function(name) {
 if (!$scope.search){
   return true;
 }else
    var regex = new RegExp('\b' + escRegExp($scope.search), 'i');
    return regex.test(name.split(' ')[0]);
};  
}
    
18.09.2014 / 21:51
0

You can create a custom filter and register it in the angle.

1 - Create a module

var app = angular.module('app',[]);
<html ng-app="app">

2 - Register the controller in this module

app.controller('List',List)

3 - Create the filter

app.filter('firstType',function(){
  return function(input, type){
    var results = [];
    for(var i in input){
      var name = input[i];
        if(name[0]==type)
            results.push(name);
    }
    return results;
  };
});

4 - Call the filter

<div ng-controller="List">
  <ul>
    <li ng-repeat="name in names | firstType: filterSearch">{{name}}</li>
  </ul> 
  <div>
    <input type="search" ng-model="filterSearch">
  </div>
</div>

Some links to help:

02.10.2014 / 13:46