2017-06-25 164 views
0

这是这个问题的延续:How to display comma delimited JSON value as a list?显示逗号分隔值列表项:

我有此数组:

var ARTISTS: Artist[] = [ 
    { 
    "name": "Barot Bellingham", 
    "shortname": "Barot_Bellingham", 
    "reknown": "Royal Academy of Painting and Sculpture", 
    "bio": "Some bio here...", 
    "friends": [ 
     "james", 
     "harry", 
     "bob" 
    ] 
    }, 
    // etc... 
] 

,我需要显示“朋友”作为一个有序列表。我这样做是这样的:

<li *ngFor="let friend of artist.friends">{{friend}}</li> 

这工作完全,,我现在需要调整自己的数据,因此没有嵌套数组:

var ARTISTS: Artist[] = [ 
    { 
    "name": "Barot Bellingham", 
    "shortname": "Barot_Bellingham", 
    "reknown": "Royal Academy of Painting and Sculpture", 
    "bio": "Some bio here...", 
    "friends": "James, Harry, Bob" 
    } 

我怎样才能继续显示每个朋友作为单独的列表项,如:

<ol> 
    <li>James</li> 
    <li>Harry</li> 
    <li>Bob</li> 
</ol> 

谢谢!

回答

0

只需使用toString()方法显示用逗号分隔的字符串列表。

var friends = ['a', 'b', 'c']; 
 
console.log(friends.toString());

所以你的情况,你可以只改变这一点:

<li *ngFor="let friend of artist.friends">{{friend}}</li> 

这个例如:

<div>{{artist.friends.toString()}}</div> 

如果要更改分隔符,或在逗号后面添加空格,则可以使用阵列方法太:

var friends = ['a', 'b', 'c']; 
 
console.log(friends.join(', '));

相反,如果现在你在你的模型有列表,用逗号分隔的字符串,请使用ng-repeat重建从字符串数组中这样说:

<li *ngFor="let friend of artist.friends.split(', ')">{{friend}}</li> 
+0

感谢您的帮助,quirimmo!但是,我担心我的问题有点不清楚。在问题的最底部看到我的编辑:通过列表项,我的字面意思是'

  • James
  • Harry
  • Bob
  • '。我无法将这个逗号分隔值渲染到每个朋友包裹在'
  • '标记中的位置。或者,你的回答解释了这一点,我只是误解?谢谢! – Boosman

    +0

    我想我现在得到了你,编辑了答案。其实你应该可以这样做:'

  • {{friend}}
  • ' – quirimmo

    +0

    谢谢!正是我想要做的。有时候,这些小东西把我搞砸了! – Boosman