AngularJS学习之旅—AngularJS 过滤器(七)

1、AngularJS 过滤器
  过滤器可以使用一个管道字符(|)添加到表达式和指令中。
  AngularJS 过滤器可用于转换数据:
  过滤器 描述
    currency 格式化数字为货币格式。
    filter 从数组项中选择一个子集。
    lowercase 格式化字符串为小写。
    orderBy 根据某个表达式排列数组。
    uppercase 格式化字符串为大写。

实例

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <script src="js/angular.min.js"></script>
</head>

<body>
    <div ng-app="myApp" ng-controller="myCtrl">
        <!-- uppercase 过滤器将字符串格式化为大写 -->
        <p>姓名为 {{ lastName | uppercase }}</p>
        <!-- lowercase 过滤器将字符串格式化为小写 -->
        <p>姓名为 {{ lastName | lowercase }}</p>
        <!-- currency 过滤器将数字格式化为货币格式 -->
        数量: <input type="number" ng-model="quantity">
        价格: <input type="number" ng-model="price">
        <p>总价 = {{ (quantity * price) | currency }}</p>
        <!-- orderBy 过滤器根据表达式排列数组 -->
        <ul>
            <li ng-repeat="x in names | orderBy:'country'">
                {{ x.name + ', ' + x.country }}
            </li>
        </ul>
        <!-- filter 过滤器从数组中选择一个子集 -->
        <p><input type="text" ng-model="test"></p>
        <ul>
            <li ng-repeat="x in names | filter:test | orderBy:'country'">
                {{ (x.name | uppercase) + ', ' + x.country }}
            </li>
        </ul>
        <!-- 自定义过滤器 -->
        姓名: {{ firstName | reverse }}
    </div>
</body>

</html>
<script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function ($scope) {
        $scope.firstName = "John";
        $scope.lastName = "Doe";
        $scope.names = [{
                name: 'Jani',
                country: 'Norway'
            },
            {
                name: 'Hege',
                country: 'Sweden'
            },
            {
                name: 'Kai',
                country: 'Denmark'
            }
        ];
    });
     // 自定义过滤器
     app.filter('reverse', function() { //可以注入依赖
            return function(text) {
                return text.split("").reverse().join("");
            }
        });
</script>

页面展示

猜你喜欢

转载自www.cnblogs.com/songjianhui/p/10289076.html