angularjs内置服务_关于内置AngularJS过滤器的所有信息

angularjs内置服务

介绍 (Introduction)

You may not know this - but AngularJS comes with many handy filters built-in. I see programmers reinventing the wheel and reimplementing functionality that already exists all the time. Sometimes this happens because you need to address a specific use case but more often than not, it's simply because the programmer wasn't aware that the functionality was already there.

您可能不知道-但是AngularJS内置了许多方便的过滤器。 我看到程序员重新发明了轮子,重新实现了一直存在的功能。 有时候,发生这种情况是因为您需要解决一个特定的用例,但更多时候不是这样,这仅仅是因为程序员并不知道该功能已经存在。

In this article, I will go over the many filters that AngularJS provides out of the box. Most of these are documented in the Angular Docs but lack real world examples, so I will approach this topic with a plethora of code samples and real world uses.

在本文中,我将直接使用AngularJS提供许多过滤器 。 其中大多数已在Angular Docs中进行了记录,但缺少实际示例,因此我将通过大量代码示例和实际使用来探讨该主题。

Let's jump right into it!

让我们跳进去吧!

应用和使用过滤器 (Applying and Using Filters)

Filters, as the name implies, allow you to manipulate and filter the presentation of your views. You can apply Angular filters directly by extending the bindings in your HTML views such as:

顾名思义,过滤器使您可以操纵和过滤视图的表示 。 您可以通过在HTML视图中扩展绑定来直接应用Angular过滤器,例如:

基本过滤器语法 (Basic Filter Syntax)

{{ totalCost | currency }}

链式过滤器 (Chaining Filters)

Filters can also be chained, by adding the pipe ( | ) character between each filter so if we wanted to apply multiple filters to a single expression it would look something like:

通过在每个过滤器之间添加竖线(|)字符,也可以将过滤器链接起来,因此,如果我们想将多个过滤器应用于单个表达式,它将类似于:

{{ totalCost | currency | filter2 | filter3 }}

扩展过滤器 (Extended Filters)

Finally, filters can be extended even further by supporting arguments, for example:

最后,可以通过支持参数进一步扩展过滤器,例如:

{{ totalCost | currency:"USD$" }}

It is common practice to apply filters directly to the binding expressions in the HTML views, but you can also apply filters in your controllers and directives as well.

通常将过滤器直接应用于HTML视图中的绑定表达式,但是您也可以在控制器和指令中应用过滤器。

JavaScript文件内部的过滤器 (Filters Inside of JavaScript Files)

The syntax for applying filters in your JavaScript files will look like this:

在JavaScript文件中应用过滤器的语法如下所示:

$filter('number')(15, 5)

This filter is equivalent to {{ 15 | number:5 }} and both will render the number 15 as string to five decimal places (i.e. 15.00000) in your view.

此过滤器等效于{{ 15 | number:5 }} {{ 15 | number:5 }} ,两者都将数字15作为字符串呈现在视图中的小数点后五个位(即15.00000)。

It's ok if you don't fully grasp what we're doing so far, we are just going over the syntax here - next we'll walk through the built in filters and how they can improve the presentation of your apps.

如果您不完全了解我们目前正在做的事情,可以的,我们只是在这里介绍语法-接下来,我们将逐步介绍内置过滤器以及它们如何改善应用程序的表示。

字符串操作-大写和小写 (String Manipulation - Uppercase and Lowercase)

AngularJS comes with prebuilt filters for making a string upper or lower-case. The uppercase and lowercase filters will do what their name implies, either convert a string to all uppercase characters, or convert the string to all lowercase characters.

AngularJS附带有用于将字符串大写或小写的预置过滤器。 大写和小写过滤器将按照其名称的含义进行操作,将字符串转换为所有大写字符,或将字符串转换为所有小写字符。

The simplest way to apply this filter to an expression is to add it directly in the view. Please check out the Codepen below to see the Uppercase and Lowercase filters illustrated.

将此过滤器应用于表达式的最简单方法是将其直接添加到视图中。 请查看下面的Codepen以查看图示的大写和小写过滤器。

// JavaScript
app.controller('limits', function($scope){
  $scope.copy = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
  $scope.yelling = "LOREM ISPUM DOLOR SIT AMET, CONSECTETUR ADIPISCING ELIT, SED DO EIUSMOD TEMPOR INCIDIUNT UT LABORE ET DOLORE MAGNA ALIQUA."
})

// HTML
Uppercase:
{{ copy | uppercase }}

Lowercase:
{{ yelling | lowercase }}

See the Pen icDkb by Ado Kukic (@kukicadnan) on CodePen.

请参阅CodePen上 Ado Kukic( @kukicadnan )的Pen icDkb

数字处理-数字和货币 (Number Manipulation - Numbers and Currencies)

AngularJS also comes with a couple of very useful filters for dealing with numbers and currencies. For numbers, Angular comes with the ability to filter how to number is displayed in regards to the decimal representation and rounding of numbers.

AngularJS还带有几个非常有用的过滤器,用于处理数字和货币。 对于数字,Angular可以过滤关于小数表示和数字舍入的数字显示方式。

In the Codepen below, we apply a couple of different number filters to display a whole number to four decimal places, we also use the numbers filter to round up a number to the nearest hundredth.

在下面的Codepen中,我们应用几个不同的数字过滤器将整数显示到小数点后四位,我们还使用数字过滤器将数字四舍五入到最接近的百分位。

// JavaScript
app.controller('numbers', function($scope){
  $scope.defaultNumber = 50;
  $scope.defaultNumberDecimals = 50.458;
})

// HTML
Default Number Filter:
{{ defaultNumber | number }}

Number to Four Decimal Places:
{{ defaultNumber | number:4 }}

Round Number to Two Decimal Places:
{{ defaultNumberDecimals | number:2 }}

See the Pen KAzlr by Ado Kukic (@kukicadnan) on CodePen.

CodePen上查看Ado Kukic( @kukicadnan )的Pen KAzlr

Part two of number manipulation deals with currencies and AngularJS filters really shine here. By default if we apply the currency filter to a number, it will simply add a $ symbol before the number.

数字处理涉及货币和AngularJS过滤器的第二部分确实在这里大放异彩。 默认情况下,如果我们将货币过滤器应用于一个数字,它将在该数字之前简单地添加一个$符号。

This works really well if you are writing an app that will only deal with dollars, but what if we wanted to localize the app to support a variety of currencies? We can simply expand the currency filter by passing in some parameters to the filter.

如果您正在编写仅处理美元的应用程序,则此方法非常有效,但是如果我们要本地化该应用程序以支持多种货币怎么办? 我们可以简单地通过将一些参数传递给货币过滤器来扩展货币过滤器。

For example if we wanted to display the currency in euros, our code would look like {{ totalCost | currency:'€' }}. Additionally, in Angular 1.3+, the currency filter can further be expanded to support rounding up of numbers to as many decimal places as you want - or none at all.

例如,如果我们想以欧元显示货币,我们的代码将类似于{{ totalCost | currency:'€' }} {{ totalCost | currency:'€' }} 。 此外,在Angular 1.3+中,可以进一步扩展货币过滤器,以支持将数字四舍五入到所需的小数位数-或根本不舍入。

To specify the number of decimal places, you would again just pass another parameter to the currency filter such as {{ totalCost | currency:'$':4 }}, and this would render the number as "$15.0000" if totalCost was 15.

要指定小数位数,您可以再次将另一个参数传递给货币过滤器,例如{{ totalCost | currency:'$':4 }} {{ totalCost | currency:'$':4 }} ,如果totalCost为15,则数字将变为“ $ 15.0000”。

Check out the Codepen examples below to see this filter further illustrated.

查看下面的Codepen示例,以进一步了解此过滤器。

// JavaScript
app.controller('currencies', function($scope){
  $scope.defaultNumber = 59.99;
  $scope.defaultNumberWhole = 59;
})

// HTML
Default Currency Filter:
{{ defaultNumber | currency }}

Currency Filter on Whole Number:
{{ defaultNumberWhole | currency }}

Custom Currency Filter:
{{ defaultNumber | currency:'$COTCHES' }}

Custom Currency Filter with Decimal Point Control (Angular 1.3+):
{{ defaultNumber | currency:'£':0 }}

See the Pen eiGmD by Ado Kukic (@kukicadnan) on CodePen.

CodePen上查看Ado Kukic( @kukicadnan )的Pen eiGmD

日期和时间 (Date and Time)

The Date and Time filters that come with Angular are amazing. The Date and Time filters will take any standard ISO 8601 date/time string and parse it into hundreds of different ways to meet your every need.

Angular附带的日期和时间过滤器很棒。 日期和时间过滤器将采用任何标准的ISO 8601日期/时间字符串,并将其解析为数百种不同的方式,以满足您的各种需求。

Whether you need the full date written as Thursday, October 19, 2014, or just the year, day, month or any combination you can think of such as day first, then the actual day name, followed by the last two digits of the year and concluded by the month in shorthand notation (i.e Nov for November), AngularJS will do it for you.

您是否需要写成2014年10月19日星期四的完整日期,或者只需要年,日,月或您可以想到的任何组合,例如首先输入日期,然后输入实际的日期名称,然后输入年份的最后两位数字并以月份的缩写形式表示(即11月为11月),AngularJS会为您完成。

Parsing and manipulating date/time is often difficult and time consuming but the AngularJS filters make it a breeze. Like I said earlier, there are many different different filters you can apply here, and I could write multiple articles on all the different ways you can apply these filters, but in the interest of time I will direct you to the AngularJS docs that describe all the different parameters you can pass into the date filter and include a CodePen that shows off some of this functionality. Read more about the date filter here.

解析和处理日期/时间通常很困难并且很耗时,但是AngularJS过滤器使它变得轻而易举。 就像我之前说过的,您可以在此处应用许多不同的过滤器,并且我可以就应用这些过滤器的所有不同方式撰写多篇文章,但是为了节省时间,我将指导您访问描述所有内容的AngularJS文档。您可以将不同的参数传递到日期过滤器中,并包含一个CodePen来展示一些此功能。 在此处阅读有关日期过滤器的更多信息。

// JavaScript
app.controller('dates', function($scope){
  $scope.dateCommon = "2014-10-19";
  $scope.dateUTC = "2014-10-19T06:46:00+00:00";
})

// HTML
Default Date Filter:
{{ dateCommon | date }}

Full Date Filter:
{{ dateCommon | date:'fullDate' }}

Year Only Filter:
{{ dateCommon | date:'yyyy' }}

Custom Date Filter:
{{ dateUTC | date:"'Year:' yyyy, 'Month:' MMM, 'Day:' EEEE" }}

See the Pen gnHjr by Ado Kukic (@kukicadnan) on CodePen.

CodePen上查看Ado Kukic( @kukicadnan )的Pen gnHjr

JSON格式 (JSON)

The JSON built in filter in Angular converts a json string and prettifies it by including indentation so that the JSON is much easier to read. There really isn't anything else to say about this filter, it doesn't allow for any additional parameters to be passed into it, it simply converts an object to easily readable JSON.

Angular内置的JSON过滤器可转换json字符串,并通过包含缩进来美化它,从而使JSON更加易于阅读。 关于此过滤器,实际上没有什么可说的,它不允许将任何其他参数传递给它,它只是将对象转换为易于阅读的JSON。

Check out the simple CodePen below to see this illustrated.

查看下面的简单CodePen可以看到说明。

// JavaScript
app.controller('json', function($scope){
  $scope.userInfo = {"name": "Bob", "email": "bob@inbox", "password":"youshallnotpass", "activities": ["jogging", "swimming", "boxing"], "eligibility": true, "hasActiveDevice": false}
})

// HTML
JSON Filter:
{{ userInfo | json }}

See the Pen vcIuB by Ado Kukic (@kukicadnan) on CodePen.

请参阅CodePen上 Ado Kukic( @kukicadnan )的Pen vcIuB

限制于 (LimitTo)

The LimitTo filter, as it's name implies, allows you to limit some string or array to a certain length. For example, applying a limitTo:10 filter to a string that contains 15 characters, would only display the first 10 characters of that string.

顾名思义,LimitTo过滤器允许您将某些字符串或数组限制为一定长度。 例如,对包含15个字符的字符串应用limitTo:10过滤器,将仅显示该字符串的前10个字符。

LimitTo can also be applied to arrays and can be very powerful and intuitive when used in conjunction with ng-repeat. Combining limitTo and ng-repeat, you could very easily build a pagination system for your app for example.

LimitTo也可以应用于数组,与ng-repeat结合使用时,功能非常强大且直观。 例如,将limitTo和ng-repeat结合使用,您可以非常轻松地为您的应用构建分页系统。

One common use case where the limitTo filter can come in handy is preview text. Say you're building the front-page for your blog in AngularJS and want to show a preview of the first 250 characters of each blog post. This can easily be accomplished by the following code {{ previewCopy | limitTo: 250 }}.

可以使用limitTo过滤器的一种常见用例是预览文本。 假设您正在AngularJS中构建博客的首页,并希望显示每个博客文章的前250个字符的预览。 可以通过以下代码{{ previewCopy | limitTo: 250 }} {{ previewCopy | limitTo: 250 }}

Check out the CodePen below to see how we apply the ellipses(...) to the end if the previewCopy is over the character limit.

请查看下面的CodePen,以了解如果PreviewCopy超过字符数限制,我们如何将省略号(...)应用于结尾。

// JavaScript
app.controller('limits', function($scope){
  $scope.copy = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

  $scope.list = ['@scotch_io', '@sevilayha', '@kukicadnan', '@hollylawly', '@nickforthought', '@kenwheeler', '@mathiashansen']
})

// HTML
LimitTo Filter Applied to a String:
{{ copy | limitTo:150 }}

LimitTo Filter Applied to an Array:
<ul>
  <li ng-repeat="person in list | limitTo:4"> {{person}} </li>
</ul>

See the Pen sFoAH by Ado Kukic (@kukicadnan) on CodePen.

CodePen上查看Ado Kukic( @kukicadnan )的Pen sFoAH

结论 (Conclusion)

We've gone over all of the built-in AngularJS filters. The built-in filters provide a variety of functionality from simple uppercasing of a string to complex manipulation of dates.

我们已经研究了所有内置的AngularJS过滤器。 内置的过滤器提供各种功能,从简单的字符串大写到复杂的日期操作。

We went over the different ways to apply filters, the most common being by applying the filter directly in the binding, but I've also shown you how to apply the filter through JavaScript.

我们讨论了应用过滤器的不同方法,最常见的方法是直接在绑定中应用过滤器,但我还向您展示了如何通过JavaScript应用过滤器。

I hope this article has gotten you familiar with how AngularJS filters work because next we are going to learn to build our own filters! Stay tuned!

我希望本文使您熟悉AngularJS过滤器的工作原理,因为接下来我们将学习构建自己的过滤器! 敬请关注!

翻译自: https://scotch.io/tutorials/all-about-the-built-in-angularjs-filters

angularjs内置服务

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值