angular的filter
filter两种用法
1、在模板中使用filter
{{expression|filter}}//基本用法
{{expression|filter1|filter2|filter3}}//多个过滤器,上一段输出为下一段输入
{{expression|filter:args1,args2,...}}//带参数
除了使用简单的表达式,还可以在ng-repeat中使用,在这里我们获得处理的对象是一个数组,或者对象,不是单个的item
<span ng-repeat="a in arr|filter"></span>
2、在controller和serveice中使用filter
使用filter,在间接使用
app.controller('MyCtrl',function($scope,$filter){
$scope.num = $filter('currency')(123456);
$scope.date = $filter('date')(new Date());
});
直接使用
app.controller('MyCtrl',function($scope,currencyFilter){
$scope.num = currencyFilter(123456);
});
filter中需要注意的一点是,filter这个名字的也是一个angular本身自带的filter,用来匹配子串的。
自定义过滤器
最简单的用法
app.filter('hello',function(){
return function(input){
var str = 'hello world';
return str;
}
});
加上参数的用法
app.filter('ha',function(){
return function(input,args,args2){
var str = 'hello world'+args+args2;
return str;
}
});
filter在使用时的坑
ng-repeat中的$index
这里在使用$index就会面临,在filter出匹配的子串之后,$index的值不变化的问题,对应值就不是现在的list
<body ng-app="demo">
<p>Click the test button to see what result you would get when using <code>$index</code>
vs when using <code>item</code> directly</p>
<p>Try filtering for example for <kbd>foo</kbd> and you'll get a different result</p>
<div ng-controller="DemoCtrl">
<input type="text" ng-model="filter" placeholder="Filter the list">
<ul>
<li ng-repeat="item in items | filter:{ name: filter }">
{{item.name}}
<button ng-click="getResult($index, item)">test</button>
</li>
</ul>
<h2>Results</h2>
<p><code>$index:</code> {{indexResult.name}}</p>
<p><code>item:</code> {{itemResult.name}}</p>
</div>
</body>
var app = angular.module('demo', ['ng']);
app.controller('DemoCtrl', ['$scope', function($scope) {
$scope.items = [
{ name: 'Hello' },
{ name: 'Foobar' },
{ name: 'Barfoo' },
{ name: 'Magic' },
{ name: 'Wand' }
];
$scope.getResult = function($index, item) {
$scope.indexResult = $scope.items[$index];
$scope.itemResult = item;
};
}]);