自定义Filter服务

自定义一个用户Email长度超过12个字符后值截取前12个然后添加“...”显示。

例如:

index.html

<!DOCTYPE html>

<html ng-app="myApp">
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="../css/uikit.css"/>
        <link rel="stylesheet" href="../css/my-uikit.css"/>
    </head>
    <body>
        
        <div class="uk-panel" ng-controller="UserCtrl">
            
            <table class="uk-table uk-table-hover uk-table-striped">
                <thead>
                    <tr class="uk-bg-primary">
                        <th>Name</th>
                        <th>Email</th>
                    </tr>
                </thead>
                <tbody ng-repeat="user in users "  class="uk-text-success">
                    <tr>
                        <td>{{user.name }}</td>
                        <td>{{user.email | subStrFilter:12}}</td>
                    </tr>
                </tbody>
            </table>
        </div>
        
    </body>
    
    <script src="../js/angular.js"></script>
    <script src="index.js"></script>
</html>

 

定义的filter名称为:subStrFilter,注意function(limitToFilter),limitTo表示angular内置的limitTo过滤器,我们自定义的过滤器依赖与limitTo过滤器,参数input表示被过滤的字段值,limit表示最大长度,使用方式:

<td>{{user.email | subStrFilter:12}}</td>

index.js

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


myApp.filter('subStrFilter', function(limitToFilter){
    return function(input, limit){
        if(input.length>limit){
            return limitToFilter(input,limit-3)+'...';
        }
        
        return input;
    };
});

myApp.controller('UserCtrl', ['$scope', function($scope){
        $scope.users = [
            {
                name:'张三',
                email:'zhangsan@gmail.com'
            },
            {
                name:'李四',
                email:'lisi@123.com'
            },
            {
                name:'王五',
                email:'wangwu@qq.com'
            }
        ];
}]);

 

posted @ 2015-02-04 20:22  yshy  阅读(175)  评论(0编辑  收藏  举报