角度过滤器不会打印空格

时间:2022-05-02 03:06:50

When I have such very easy Angular filter code:

当我有这么简单的Angular过滤器代码时:

{{ 'result: ' + array | printArray }}

with filter:

带过滤器:

app.filter('printArray', [
  function() {
    return function(array) {
      if (!angular.isArray(array)) {
        return array;
      }

      var result = '';

      if (array.length > 0) {
        result = array[0];

        for (var i = 1; i < array.length; i++) {
          result += ', ' + array[i];
        }
      }
      return result;
    };
  }
]);

I would like to have naturally result: one, two, three, four, but the result is:

我想有自然的结果:一,二,三,四,但结果是:

abc one,two,three,four

I knot it would be resolved by this obvious code:

我知道它会被这个明显的代码解决:

{{ 'result: ' }}{{ array | printArray }}

but I would like to know why Angular works in weird way.

但我想知道为什么Angular以奇怪的方式工作。

Plunker: http://plnkr.co/edit/QRtntKedYHKb5UnZD3w7

Plunker:http://plnkr.co/edit/QRtntKedYHKb5UnZD3w7

2 个解决方案

#1


3  

Checkout this

看看这个

  <body ng-controller="MainCtrl">
  {{ 'result: ' + ( array | printArray ) }}

  </body>

#2


3  

in this example i used Array.join() function,
and moved the string to outside of the curly braces:

在这个例子中,我使用了Array.join()函数,并将字符串移动到花括号外:

result: {{ array | printArray }}

http://plnkr.co/edit/CRKChEtF5HafdRPV8eW4?p=preview

http://plnkr.co/edit/CRKChEtF5HafdRPV8eW4?p=preview

#1


3  

Checkout this

看看这个

  <body ng-controller="MainCtrl">
  {{ 'result: ' + ( array | printArray ) }}

  </body>

#2


3  

in this example i used Array.join() function,
and moved the string to outside of the curly braces:

在这个例子中,我使用了Array.join()函数,并将字符串移动到花括号外:

result: {{ array | printArray }}

http://plnkr.co/edit/CRKChEtF5HafdRPV8eW4?p=preview

http://plnkr.co/edit/CRKChEtF5HafdRPV8eW4?p=preview