如何初始化和更新 angular 变量

How to initialize and update angular variable

我遇到过这样一种情况,我需要在某些迭代后有条件地在 ng-repeat 中执行 HTML。

下面是一个例子:

<div>
  <p ng-init="x=1">
    These are my names....
  </p>
  <div ng-repeat="a in data.result">
    <div ng-if="a.type=='Student' && x<3">
      <span ng-init="x++">
         <br/>
        {{::a.name}} with type of {{::a.type}} and color {{::a.color}}
        </span>
    </div>    
  </div>  
</div>

脚本:

data.result =[
  {
    "color": "Red",
    "name": "IP0",
    "type": "Student"
  },
  {
    "color": "Red",
    "name": "IPwd1",
    "type": "Student"
  },
  {
    "color": "White",
    "name": "IPdw2",
    "type": "Teacher"
  },
  {
    "color": "Red",
    "name": "IPed3",
    "type": "Student"
  },
  {
    "color": "Red",
    "name": "IP4ed",
    "type": "Student"
  },
  {
    "color": "White",
    "name": "IP7h2",
    "type": "Teacher"
  }
];  

以上代码总是给出以下输出:

**These are my names....
IP0 with type of Student and color Red
IPwd1 with type of Student and color Red
IPed3 with type of Student and color Red
IP4ed with type of Student and color Red**

我只希望 HTML 到 运行 仅限前 2 名学生。

似乎'x'在执行下一个循环时总是初始化为1或者不递增。如何有条件地使其 运行 进行某些迭代?有什么想法吗?

image

这里有一个 'proper' 方法,尽管在这个例子中有点矫枉过正。您应该在 ng-repeat 列表上使用过滤器,而不是操作原始数据源。要将结果限制为某个 #,请使用 limitTo。在下面的示例中,过滤器是可扩展的。你可以做到 filterBy:{type:'Student', color:'Red'}

html:

<div ng-repeat="a in data.result | filterBy:{type:'Student'} | limitTo:2">
      {{::a.name}} with type of {{::a.type}} and color {{::a.color}}
</div> 

angular 过滤器

app.filter('filterBy', function() {
  return function(data, filters) {
    return data.filter(d => {
      let ret = true, x;
      for(x in filters) {
        if (d[x]!=filters[x]) ret = false;
      }
      return ret;
    })
  };
})

查看 Plnkr:

https://plnkr.co/edit/g72UNjTgQUtofKqo?open=lib%2Fscript.js&deferRun=1