Problem with Uppercase and Lowercase in Angularjs

Asked

Viewed 1,028 times

1

People followed the example of a script in stackoverflow.com as follows the link below: [https://stackoverflow.com/questions/19040732/filter-php-list-with-angularjs][1]

I happen to be having problems with words that are capitalized for example, a word that is "Protocol" and I type "protocol", the filter does not find it.

app js.

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
    $scope.model = {
        filter: ''
    };
});

app.directive('myHtmlFilter', [function() {
    return {
        restrict: 'A',
        scope: {
          filter: '=myHtmlFilter',
          element: '@'
        },
        link: function(scope, elem, attrs) {
          scope.$watch('filter', function(newval, oldval) {
            elem
              .find('ul>li')
                  .hide()
                  .find(scope.element)
                  .filter(':contains("'+scope.filter+'")')
               .parent()
                  .show();
          })
        }
    }
}]);

Index.html

<input type="text" ng-model="model.filter" />

<div my-html-filter="model.filter" element="h2">
  <ul>
    <li id="1">
        <h2>Protocolo</h2>
        <p>The Message...</p>
    </li>
    <li id="2">
        <h2>My second Post</h2>
        <p>The Message...</p>
    </li>
    <li id="3">
        <h2>My third Post</h2>
        <p>The Message...</p>
    </li>
  </ul>
</div>
  • In that other question you posted a solution. It would be the same answer to that question?

  • No, in this case the problem is to perform a search where when you type a word and it matches the values found independent if it is uppercase or lowercase.

1 answer

3

The problem is on the line:

.filter(':contains("'+scope.filter+'")')

The selector :contains jQuery distinguishes between upper and lower case letters (case sensitive). Function .filter() accepts as a parameter a callback that you can use to evaluate whether the element meets your criteria and whether or not it should be added to the list of filtered items.

An example of callback that makes a case insensitive comparison:

.filter(function(){ return $(this).text().toLowerCase().indexOf(scope.filter) > -1 })

In your directive it would look like this:

app.directive('myHtmlFilter', [function() {
    return {
        restrict: 'A',
        scope: {
          filter: '=myHtmlFilter',
          element: '@'
        },
        link: function(scope, elem, attrs) {
          scope.$watch('filter', function(newval, oldval) {
            elem
              .find('ul>li')
                  .hide()
                  .find(scope.element)
                  .filter(function(){ return $(this).text().toLowerCase().indexOf(scope.filter) > -1 })
               .parent()
                  .show();
          })
        }
    }
}]);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.