15

So I've been trying a while to make a custom filter that searches for the 'Startswith' parameters rather than the 'Contains'. Every filter that I've written haven't seem to work properly. Here is an example of what I'm trying to achieve ---> http://jsfiddle.net/DMSChris/9ptr9/

function FilterCtrl() {
var scope = this;
scope.doFilter = function(elem) { 
    if(!scope.searchText) return true;
    return elem.last_name.toLowerCase().indexOf( scope.searchText.toLowerCase()) == 0; 
};

}

http://jsbin.com/OyubElO/1/edit - Here is where I'm at right now.

  <ul border="1px" ng-repeat="msg in messages | filter:search:strict">

<li>{{msg.last_name}}</li>

Any help would be greatly appreciated!

1
  • If elem.last_name can be a long string, you may want to consider truncating and then comparing with === to the text to find Commented Oct 21, 2013 at 17:50

3 Answers 3

34

A simple way to do this is to add a new method to your scope.

$scope.startsWith = function (actual, expected) {
    var lowerStr = (actual + "").toLowerCase();
    return lowerStr.indexOf(expected.toLowerCase()) === 0;
}

Then change the filter syntax on your element.

<ul border="1px" ng-repeat="msg in messages | filter:search:startsWith">

Here is a working plunkr with the example above.

Sign up to request clarification or add additional context in comments.

7 Comments

@Robin I've added a plunkr with the example. What didn't work for you?
@mark plunkr doesn't seem to be there. But this worked for me!!
@Shadow thanks for letting me know! I cleaned up my plunks and accidentally deleted that one. It's recreated now.
@mark This working perfectly, i just can't understand what is expected variable needed for ?
Extended question on this which formats the filtered result. Any help is highly appreciated! stackoverflow.com/questions/46728544/…
|
3

Filter in object

  $scope.fmyData = $filter('filter')($scope.AllMyData, $scope.filterOptions,function (actual, expected) {
                    return actual.toLowerCase().indexOf(expected.toLowerCase()) == 0;
                });

1 Comment

Hi @user35.. , any working plunker, please ? it really needs me.Thanks.
0

Now pure javascript itself has the startsWith() method on strings. But it will not be supported by IE11.

See here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.