Angular JS’Startswith’自定义filter

所以我一直在尝试制作一个自定义filter来搜索’Startswith’参数而不是’Contains’。 我写的每个filter似乎都没有正常工作。 这是我想要实现的一个例子—> 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 – 这就是我现在所处的位置。

  
  • {{msg.last_name}}

任何帮助将不胜感激!

一种简单的方法是在范围中添加新方法。

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

然后更改元素的filter语法。

 

    这是一个上面的例子的工作plunkr 。

    过滤对象

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

    现在纯javascript本身在字符串上有startsWith()方法。 但它不会得到IE11支持。

    看这里:

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