angular之过滤器的使用和自定义过滤器

1、过滤器可以直接在表达式{{ }}里使用,也可以作为服务,依赖注入的形式$filter使用,例如:

$scope.name = $filer('uppercase')('hello');//第一个括号写要使用哪种过滤器,第二个括号写要过滤的参数
$scope.name = $filer('number')('18526.1335855', 3);

2、自定义过滤器的使用跟angular自身的过滤器的使用是一样的,如何自定义过滤器呢?

<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <script src="angular.min.js"></script>
</head>
<body>
  <div ng-controller="aaa">{{name | firstUpper: 2}}</div>

  <script>
    var m1 = angular.module('myApp', []);
    m1.filter('firstUpper', function(){
      return function(str, number) {
        console.log(number);
        return str.charAt(0).toUpperCase() + str.substring(1);
      }
    });
    m1.controller('aaa', ['$scope', function($scope) {
      $scope.name = "xiaoxiao";
    }]);
  </script>
</body>
</html>



猜你喜欢

转载自blog.csdn.net/rose999ying/article/details/80853072