如何使用角度过滤器将字符串转换为数组并在`ng-repeat`中使用

时间:2015-08-09 06:11:22

标签: angularjs angular-filters

我正从后端收到一个字符串。需要转换为数组然后它需要发送ng-repeate,该怎么做?

我熟悉使用array值操作的过滤器。但如何将字符串转换为数组以进行“ng-repeate”

我更喜欢使用过滤器进行通用。

这是代码:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';

  $scope.string = "1. Submittals in progress 2. Structural works in progress in S2 & S3 3. Structural works in progress in N4. 4. Childrens Mall pedestal and steel fabrication."


});

app.filter('string2array', function( string ) {

    return string.match(/\b\d+\.\s+(.+?)\s*(?=\b\d+\. |\s*$)/g); //converted as array.

});

HTML:

 <p>Hello {{name}}!</p>
    <ul>
      <li ng-repat="item in string">{{string}}</li>
    </ul>

Live Demo

我看起来像这样:

<ul>
<li> Submittals in progress </li> //see the number removed.
<li> Structural works in progress in S2 & S3 </li>
<li> Structural works in progress in N4. </li> //end has the dot
<li> Childrens Mall pedestal and steel fabrication. </li>
</ul>

1 个答案:

答案 0 :(得分:1)

  1. 更改您的过滤器语法:

    var app = angular.module('plunker', []);
    
    app.controller('MainCtrl', function($scope) {
      $scope.name = 'World';
    
    $scope.string = "1. Submittals in progress 2. Structural works in progress in S2 & S3 3. Structural works in progress in N4. 4. Childrens Mall pedestal and steel fabrication."
    
    
    });
    
    app.filter('string2array', function() {
        return function(string){
           return string.match(/\b\d+\.\s+(.+?)\s*(?=\b\d+\. |\s*$)/g);    //converted as array.
       }
    } );
    
  2. 使用HTML中的过滤器:

    <p>Hello {{name}}!</p>
     <ul>
      <li ng-repeat="item in string | string2array">{{item}}</li>
    </ul>
    
  3. 见编辑plunker