Search code examples
angularjsangular-filters

How to convert a string to an array using angular filter and use in `ng-repeat`


I am receving a string from back-end. that need to be converted as an array then it need to send on ng-repeate, how to do that?

i ma familiar filter for using array value manipulation. but how to convert a string in to an array for `ng-repeate'

I am preferring filter for generic usage.

here is the code :

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

I am looking the out put like this:

<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>

Solution

    1. Change your filter syntax like this:

      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. use the filter in the HTML like this:

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

    see edited plunker