使用ng-repeat打印对象数组

时间:2015-12-18 12:58:18

标签: javascript angularjs ng-repeat

我有一组像下面这样的对象。

Signatures = [{
    "Name": "Person 1",
    "Status": "New"
}, {
    "Name": "Person 2",
    "Status": "New"
}, {
    "Name": "Person 3",
    "Status": "Completed"
}, {
    "Name": "Person 4",
    "Status": "Cancelled"
}];

我想根据状态以下列方式按照每个对象的“名称”打印列表。

New : Person 1 , Person 2
Completed : Person 3 
Cancelled : Person 4

我尝试过3 ng-repeats。每个包含一个ng-if用于比较Status是New,Completed还是Cancelled。但我正在寻找更好的解决方案。在此先感谢您的任何帮助

这是JSfiddle http://jsfiddle.net/HB7LU/21355/

4 个答案:

答案 0 :(得分:4)

修改你的dom以使用过滤器

<div ng-controller="MyCtrl">
<div>
New 
  <span ng-repeat="signer in Signatures | filter : {Status : 'New'}">
      <span>
                  <b>{{signer.Name}}</b>
      </span>
  </span>
</div>

<div>
Completed 
  <span ng-repeat="signer in Signatures | filter : {Status : 'Completed'}">
      <span>
                  <b>{{signer.Name}}</b>
      </span>
  </span>
</div>

<div>
Cancelled 
  <span ng-repeat="signer in Signatures | filter : {Status : 'Cancelled'}">
      <span>
                  <b>{{signer.Name}}</b>
      </span>
  </span>
</div>

</div>

这将按预期工作。

<强> See jsfiddle

答案 1 :(得分:1)

因为不支持 angular-1.0.1.js ng-if。您可以使用ng-hideng-show

AngularJS首先在1.1.5中添加了ng-if指令。请更新角度版本。

<div ng-controller="TestCtrl">

    New: <span ng-repeat="signer in Signatures" ng-if="signer.Status=='New'">
      <b>{{signer.Name}}</b>
    </span>
    </br>
    Completed: <span ng-repeat="signer in Signatures" ng-if="signer.Status=='Completed'">
      <b>{{signer.Name}}</b>
     </span>
     </br>
    Cancelled: <span ng-repeat="signer in Signatures" ng-if="signer.Status=='Cancelled'">
          <b>{{signer.Name}}</b>
     </span>


 <div>

这将按预期工作。

<强> Example code.

答案 2 :(得分:1)

只需尝试此代码即可。这是有效的:

<div ng-controller="MyCtrl">
<span>New: </span>
<span ng-repeat="signer in Signatures|filter: { Status: 'New' } ">
    <span ng-if="signer.Status=='New'">
        <b>{{signer.Name}}</b>
    </span>
</span>
<br />
<span>Completed: </span>
<span ng-repeat="signer in Signatures|filter: { Status: 'Completed' } ">
    <span ng-if="signer.Status=='New'">
        <b>{{signer.Name}}</b>
    </span>
</span>
<br />
<span>Cancelled: </span>
<span ng-repeat="signer in Signatures|filter: { Status: 'Cancelled' } ">
    <span ng-if="signer.Status=='New'">
        <b>{{signer.Name}}</b>
    </span>
</span>

答案 3 :(得分:0)

由于angular-1.0.1.js不支持ng-if,你可以使用另一种替代方法

angular.foreach(Signatures,function(value,key){
      if(value.Status=='New') {
           Signatures.pop(key);
      }
});