Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

javascript - How can i use an angular js filter to format values in an array

I've used angular filters to do all kinds of fun formatting, but always on primitive values. For example, filtering numbers into a currency format.

How would I do that same kind of filtering for an array of values? For example

price = 1
prices = [1,2,3]

Assuming currency is the currency filter mentioned in https://docs.angularjs.org/api/ng/filter/currency

{{price | currency}} 

would return $1.00

I would like

{{prices | currency}} 

to return [$1.00,$2.00,$3.00]

how can i write a filter that does that? Or is there a different tool i should be using?

For more background...I'm using this array inside of the angular-selectize plugin. I don't have the option of using ng-repeat on my values.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The currency filter applies to a single value. If you want a filter that applies to an array, you need to add your own, such as:

angular.module('yourModule')
.filter('currenyArray', function($filter) {
  return function(input, uppercase) {
    input = input || [];
    var out = [];
    for (var i = 0; i < input.length; i++) {
      out.push($filter('currency')(input[i]))
    }
    return out;
  };
})

However this will return an array. If you do want to write the array, you need to adapt the function to compute a string instead of an array.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...