Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
806 views
in Technique[技术] by (71.8m points)

angularjs search and ignore spanish characters

I'm adding a simple sort on a page. The idea is to search products. These products are written in spanish language and has accents. For example: 'Jamón'.

Here is my code:

<div class="form-inline">
  <label>Search</label>
  <input type="text" ng-model="q"/>
</div>

<div ng-repeat="product in products_filtered = (category.products | filter:q | orderBy:'name')">
           ....
</div>

The only problem i have is that you have to type in "Jamón" in order to find the product "Jamón". What I want is to be more flexible, if the user types in "Jamon", the results must include "Jamón".

How can i search with angular filters and forget about accents? Any Idea?

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You'll need to create a filter function (or a full filter). This is the simplest thing that could possibly work:

HTML

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

Javascript

function Ctrl($scope) {
    function removeAccents(value) {
        return value
            .replace(/á/g, 'a')            
            .replace(/é/g, 'e')
            .replace(/í/g, 'i')
            .replace(/ó/g, 'o')
            .replace(/ú/g, 'u');
    }

    $scope.ignoreAccents = function(item) {               
        if (!$scope.search) return true;       

        var text = removeAccents(item.toLowerCase())
        var search = removeAccents($scope.search.toLowerCase());
        return text.indexOf(search) > -1;
    };

    $scope.names = ['Jamón', 'Andrés', 'Cristián', 'Fernán', 'Raúl', 'Agustín'];
};

jsFiddle here.

Please notice that this only works for arrays of strings. If you want to filter a list of objects (and search in every property of every object, like Angular does) you'll have to enhance the filter function. I think this example should get you started.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...