且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Angularjs自定义过滤器和依赖注入

更新时间:2022-12-11 11:38:42

我认为Angular工厂,服务,过滤器,指令包装器都是使用Angular风格创建JavaScript对象和函数的烤箱。所以,从Vasiliy的答案借用相同的风格:

I think of Angular factory, service, filter, directive wrappers as ovens that create JavaScript objects and functions with Angular flavors. So, to borrow the same style from Vasiliy's answer:

// Don't use this code in a real app. It's just to illustrate a point.
angular.module('App', [])

// The following oven makes an Angular flavored JavaScript function that 
// formats a currency
.service('currencyBadFilterFn',
  // We inject a built-in Angular filter, currencyFilter, into our oven
  function(currencyFilter) { 
    // oven produces a function that can be used in other places in Angular code
    return function(number) {
      // produced function returns a currency-formatted number when used
      return currencyFilter(number)   
    }
  }
)

.controller('MainCtrl',
  function($scope, currencyBadFilterFn) {
    $scope.amount = currencyBadFilterFn(10) // $10.00
  }
)

如您所见,在创建服务时使用相同的模式。在这里,我们正在创建一个服务,它返回一个我们可以在代码中的其他地方使用的函数。

As you can see, the same pattern is used in creating services. Here, we are creating a service that returns a function that we can use in other places in our code.

第一个函数,烤箱函数,以及 .service .factory .filter 包装器,告诉Angular如何建立你的功能。第一个函数的返回值是您将在代码中使用的函数。

The first function, the oven function, along with the .service or .factory or .filter wrapper, tells Angular how to build your function. The return value of that first function is what you will use in your code.