简体   繁体   English

如何在有角度的对象数组上进行迭代,但仅使用{{}}显示属性?

[英]How to iterate over object array in angular but display only property with {{}}?

Suppose we have an object array: 假设我们有一个对象数组:

    var items = [
  {
    id: 1,
    name: 'name1'
  }, {
    id: 2,
    name: 'name2'
  },
  {
    id: 3,
    name: 'name3'
  }
];

and we want to iterate over it in HTML using this: 我们想要使用以下代码在HTML中进行迭代:

{{ctrl.items}}

expecting this in the UI: 在用户界面中期望这样:

name1, name2, name3

Is this possible? 这可能吗? Or do I have to use a ngRepeat for that? 还是我必须为此使用ngRepeat?

I want to mainly do this to take advantage of the limitTo filter inside the {{}} 我主要要这样做是为了利用{{}}内的limitTo过滤器

you can use code like this in your HTML 您可以在HTML中使用这样的代码

{{ctrl.getNames(ctrl.items)}}

and in your controller add this function 并在您的控制器中添加此功能

this.getNames = function(items){
     return items.map(function(item){return item.name;}).join(", ");
}

or you can make a filter for this ,, 或者您可以为此过滤器,

app.filter("names",function(){
   return function(input){
      return input.map(function(item){return item.name;}).join(", ");
   };
});

and in your HTML use this 在您的HTML中使用

{{ctrl.items | names}}

You can accomplish this by using both ng-repeat and the limitTo filter: 您可以同时使用ng-repeat和limitTo过滤器来完成此操作:

<div ng-repeat="item in items | limitTo: 3">{{ item.name }}</div>

EDIT : 编辑

Here is a working plunkr. 这是一个正在工作的朋克。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM