1. 程式人生 > >angular之過濾器的使用和自定義過濾器

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>