自定义构建_构建自定义AngularJS过滤器

自定义构建

Not too long ago we took a look at some of the built-in Angular filters. The built-in filters cover many common use cases including formatting dates, currencies, limiting the number of items displayed and more. These filters are both useful and give insights into how we may improve our workflow when building Angular apps.

不久之前,我们看了一些内置的Angular过滤器。 内置过滤器涵盖了许多常见的用例,包括格式化日期,货币,限制所显示项目的数量等等。 这些过滤器不仅有用,而且可以深入了解我们在构建Angular应用程序时如何改善工作流程。

Today, we will build our own custom AngularJS filters. We'll start simple and build a couple filters that manipulate numbers and strings, then we'll build a filter that manipulate an entire data set. Finally, in our previous article where we discussed the built in AngularJS filters, Pierre-Adrien asked how we could use the built in Angular currency filter to display the currency denomination after the amount (i.e. 9.99$ instead of $9.99) as is common in some places of the world. Unfortunately, the built-in currency filter does not support this functionality, so we'll build our own that does!

今天,我们将构建自己的自定义AngularJS过滤器。 我们将从简单开始,并构建几个操作数字和字符串的过滤器,然后构建一个操作整个数据集的过滤器。 最后,在我们之前的文章中,我们讨论了内置AngularJS过滤器,Pierre-Adrien问我们如何使用内置Angular货币过滤器来显示金额后的货币面额(即9.99 $而不是$ 9.99),这在某些情况下很常见。世界各地。 不幸的是,内置的货币过滤器不支持此功能, 因此我们将构建自己的功能!

角度滤镜的解剖 (Anatomy of an Angular Filter)

Angular exposes a simple API for creating a filter. Just as you would declare a controller with app.controller(‘myCtrl', function(){});, you can create a new filter by appending .filter(‘filterName', function(){}) to your Angular app.

Angular公开了一个用于创建过滤器的简单API。 就像您使用app.controller('myCtrl', function(){});声明控制器app.controller('myCtrl', function(){}); ,您可以通过将.filter('filterName', function(){})附加到Angular应用中来创建新的过滤器。

A filter is very similar to an factory or service in many regards but has the added advantage of behaving on a global scope once created. As we have previously seen, you can invoke a filter on both the data binding in your html or directly inside of your controller or directive by using the $filter service. Let's break down the structure of a filter.

过滤器在许多方面与工厂或服务非常相似,但具有创建后在全局范围内运行的附加优点。 如前所述,您可以使用$filter服务在html中的数据绑定上或直接在控制器或指令内部调用过滤$filter 。 让我们分解一下过滤器的结构。

// To declare a filter we pass in two parameters to app.filter

// The first parameter is the name of the filter 
// second is a function that will return another function that does the actual work of the filter

app.filter('myFilter', function() {

  // In the return function, we must pass in a single parameter which will be the data we will work on.
  // We have the ability to support multiple other parameters that can be passed into the filter optionally
  return function(input, optional1, optional2) {

    var output;

    // Do filter work here

    return output;

  }

});

This may seem confusing from the get go, so let's jump to some examples that will demystify writing custom filters.

从一开始,这似乎令人困惑,所以让我们跳到一些示例,这些示例将使编写自定义过滤器神秘化。

我们的第一个自定义过滤器 (Our First Custom Filter)

Let's start off slow and simple. The first custom filter we'll write will convert numbers to their ordinal values, meaning that if we apply our ordinal filter to say the number 43, what will be displayed is "43rd". Let's look at the code for our ordinal filter.

让我们开始缓慢而简单。 我们将编写的第一个自定义过滤器会将数字转换为它们的序数值,这意味着如果我们将序过滤器应用为数字43,将显示的是“ 43rd”。 我们来看一下序数过滤器的代码。

// Setup the filter
app.filter('ordinal', function() {

  // Create the return function
  // set the required parameter name to **number**
  return function(number) {

    // Ensure that the passed in data is a number
    if(isNaN(number) || number < 1) {

      // If the data is not a number or is less than one (thus not having a cardinal value) return it unmodified.
      return number;

    } else {

      // If the data we are applying the filter to is a number, perform the actions to check it's ordinal suffix and apply it.

      var lastDigit = number % 10;

      if(lastDigit === 1) {
        return number + 'st'
      } else if(lastDigit === 2) {
        return number + 'nd'
      } else if (lastDigit === 3) {
        return number + 'rd'
      } else if (lastDigit > 3) {
        return number + 'th'
      }

    }
  }
});

Applying this filter to our views is straightforward:

将此过滤器应用于我们的视图很简单:

{{ 25 | ordinal }}

will yield 25th. If we were to apply the ordinal filter to a string, such as

将产生25 。 如果我们将序数过滤器应用于字符串,例如

{{ 'not a number lol' | ordinal }}

we would simply get the string not a number lol back.

我们只是简单地得到字符串而不是数字大声笑

It is a good practice to ensure you have appropriate data to filter, and if you do not simply return the unmodified data back. Take a look at the CodePen below for some additional examples.

良好的做法是确保有适当的数据要过滤,并且如果您不简单地将未修改的数据返回,则是一个好习惯。 请查看下面的CodePen,以获取其他示例。

See the Pen AngularJS Custom Filter - Ordinal Numbers by Ado Kukic (@kukicadnan) on CodePen.

见笔AngularJS自定义过滤器-序数由阿土Kukic( @kukicadnan )上CodePen

利用自定义过滤器 (Capitalizing on Custom Filters)

Sorry for the bad joke. The next custom filter we build will capitalize either the first letter or a letter we specify. The additional parameter will specify which letter to capitalize, if no additional parameter is passed than the first letter will be capitalized.

对不起这个恶作剧。 我们构建的下一个自定义过滤器将大写第一个字母或指定的字母。 如果没有传递额外的参数而不是第一个字母,则附加参数将指定要大写的字母。

This is a bit of a contrived example and has no real practical uses but we'll use it to show off how you could extend your filters.

这是一个虚构的示例,没有实际用途,但我们将用它来展示如何扩展过滤器。

// Setup the filter
app.filter('capitalize', function() {

  // Create the return function and set the required parameter as well as an optional paramater
  return function(input, char) {

    if (isNaN(input)) {

      // If the input data is not a number, perform the operations to capitalize the correct letter.
      var char = char - 1 || 0;
      var letter = input.charAt(char).toUpperCase();
      var out = [];

      for (var i = 0; i < input.length; i++) {

        if (i == char) {
          out.push(letter);
        } else {
          out.push(input[i]);
        }

      }

      return out.join('');

    } else {
      return input;
    }

  }

});

Again, applying this filter is very simple. If we wanted to capitalize a specific letter, we could pass the optional parameter such as:

同样,应用此过滤器非常简单。 如果我们要大写一个特定的字母,我们可以传递可选参数,例如:

{{ 'onomatopoeia' | capitalize:3 }}

and this would return the result of onOmatopoeia.

这将返回onOmatopoeia的结果。

See the Pen AngularJS Custom Filter - Capitalize by Ado Kukic (@kukicadnan) on CodePen.

请参阅CodePen上的Pen AngularJS自定义过滤器-由Ado Kukic( @kukicadnan )进行大写

实际过滤的过滤器 (Filters That Actually Filter)

In the previous examples, we applied filters to single items, now let's apply a filter to a collection. In this example, we will actually filter a data set.

在前面的示例中,我们将过滤器应用于单个项目,现在让我们将过滤器应用于集合。 在此示例中,我们实际上将过滤数据集。

In programming, there are hundreds of ways to reach the end goal, and in this example what we'll filter a list and return only the items that match a certain criteria.

在编程中,有数百种方法可以达到最终目标,在此示例中,我们将过滤列表并仅返回符合特定条件的项目。

We will go through a list of programming languages and display only the statically typed ones. Easy enough right?

我们将浏览编程语言列表,并仅显示静态类型的语言。 很容易吧?

// Setup the filter
app.filter('staticLanguage', function() {

  // Create the return function and set the required parameter name to **input**
  return function(input) {

    var out = [];

    // Using the angular.forEach method, go through the array of data and perform the operation of figuring out if the language is statically or dynamically typed.
    angular.forEach(input, function(language) {

      if (language.type === 'static') {
        out.push(language)
      }

    })

    return out;
  }

});

See the Pen AngularJS Custom Filter - Static Language by Ado Kukic (@kukicadnan) on CodePen.

见笔AngularJS自定义过滤器-静态语言被ADO Kukic( @kukicadnan )上CodePen

自定义货币 (Custom Currencies)

In the first example, we looked at creating a simple custom filter that only did one thing (and hopefully did that one thing well). Next, let's take a look at how we can create a filter that accepts additional parameters.

在第一个示例中,我们着眼于创建一个简单的自定义过滤器,该过滤器仅做一件事情(并希望做得很好)。 接下来,让我们看一下如何创建一个接受其他参数的过滤器。

The idea for this filter comes from Pierre Adrian who was wondering whether the built-in currency filter supports the ability to choose what side the currency symbol goes on. Unfortunately, it does not, so we'll build our own custom currency filter that does!

这个过滤器的想法来自Pierre Adrian,他想知道内置的货币过滤器是否支持选择货币符号在哪一边的功能 。 不幸的是,事实并非如此,因此我们将构建自己的自定义货币过滤器!

In the US it is standard practice to place the $ symbol before the amount (i.e. $9.99), but in certain countries it is customary to place the symbol after the amount (i.e 9.99$).

在美国,通常将$符号放在金额(即9.99美元)之前,但是在某些国家/地区习惯上将符号放在金额(即9.99 $)之后。

For our custom filter, we will allow the user to pass two parameters. The first will be the symbol or string they want to use to denote the currency, and second a true or false boolean value that will determine whether the symbol is added before or after the amount.

对于我们的自定义过滤器,我们将允许用户传递两个参数。 第一个是他们要用来表示货币的符号或字符串,第二个是确定布尔值的truefalse布尔值,该值将确定是在金额之前还是之后添加符号。

We will default the symbol to the dollar sign ($) and the position to before of the amount so that if those aren't passed the filter still works.

我们会将符号默认设置为美元符号( $ ),并将位置默认设置为金额前的位置,这样,如果未通过这些设置,则过滤器仍然有效。

// Setup the filter
app.filter('customCurrency', function() { 

  // Create the return function and set the required parameter name to **input**
  // setup optional parameters for the currency symbol and location (left or right of the amount)
  return function(input, symbol, place) {

    // Ensure that we are working with a number
    if(isNaN(input)) {
      return input;
    } else {

      // Check if optional parameters are passed, if not, use the defaults
      var symbol = symbol || '$';
      var place = place === undefined ? true : place;

      // Perform the operation to set the symbol in the right location
      if( place === true) {
        return symbol + input;
      } else {
        return input + symbol;
      }

    }
  }

});

One thing to note when dealing with filters that support multiple parameters: you must pass the parameters in the correct order! You do not have to pass all the parameters, so in our custom currency filter it is perfectly acceptable to pass only the symbol, but you cannot only pass the location of where you want the symbol to display.

处理支持多个参数的过滤器时要注意的一件事: 必须以正确的顺序传递参数! 您不必传递所有参数,因此在我们的自定义货币过滤器中,仅传递符号是完全可以接受的,但是您不能仅传递希望符号显示的位置。

If you wanted to change only the order, you would still need to pass in the symbol such as {{ 25 | customCurrency:'$':false }}.

如果您只想更改订单,则仍需要传递诸如{{ 25 | customCurrency:'$':false }} {{ 25 | customCurrency:'$':false }}

See the Pen AngularJS Custom Filter - Custom Currency by Ado Kukic (@kukicadnan) on CodePen.

见笔AngularJS自定义过滤器-自定义货币被ADO Kukic( @kukicadnan )上CodePen

结论 (Conclusion)

Today we built our own custom AngularJS filters. We learned how to create filters from scratch, built filters that did single tasks and created filters that had extended functionality. Filters can be a powerful tool for extending the presentation of your applications. What are some custom filters you would like to see?

今天,我们构建了自己的自定义AngularJS过滤器。 我们学习了如何从头开始创建过滤器,如何构建完成单个任务的过滤器以及如何创建具有扩展功能的过滤器。 筛选器可以是扩展应用程序表示的强大工具。 您想看到哪些自定义过滤器?

翻译自: https://scotch.io/tutorials/building-custom-angularjs-filters

自定义构建

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值