agstudy
agstudy

Reputation: 121568

split a string (ng-model) created inside ng-repeat directive

I start to play with angularjs, and having this data model :

friends = [
    {name:'John**amine**allo'},
    {name:'Mary**aaa**mmm'},
    {name:'Mike**bb**kkk'}
]

I would like to split each name by '**' to create a table of names.

I don't know if there is more straightforward way to do this ( maybe using some filter in angular-filter module) but here what I have so far tried:

 <table id="searchObjResults">
    <tr><th>Name</th></tr>
    <tr ng-repeat="x in friends">
      <td ng-repeat="y in x.split('**')">
        {{y}}
      </td>
    </tr>

thanks in advance for any help.

Upvotes: 2

Views: 1785

Answers (2)

dfsq
dfsq

Reputation: 193261

You need to split name property if the x elements:

<td ng-repeat="y in x.name.split('**')">{{y}}</td>

However this is probably not very good idea what you are trying to do. First of all, you need to take care of proper table structure (correct header colspan values). Secondary, it's better to render already processed data structure, rather then converting values inside templates. It just makes it overcomplicated, not to mention makes watch expression slower.

Demo: http://plnkr.co/edit/5PXTW1gjpKwg7e3S6hRM?p=preview

Upvotes: 1

A. Rodas
A. Rodas

Reputation: 20679

You can use a custom filter to specify the separator:

<table id="searchObjResults">
<tr><th>Name</th></tr>
<tr ng-repeat="x in friends">
  <td ng-repeat="y in x.name | mysplit:'**'">
    {{y}}
  </td>
</tr>
</table>

JS:

app.filter('mysplit', function() {
  return function(data, sep) {
    return data.split(sep);
  }
});

Plunker

Upvotes: 1

Related Questions