【问题标题】:How to initialize and update angular variable如何初始化和更新角度变量
【发布时间】:2022-01-01 17:07:18
【问题描述】:

我遇到了一个场景,我需要在某些迭代后有条件地在 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

【问题讨论】:

  • 我认为最简单的方法是在javascript中过滤data.result。

标签: javascript html angularjs servicenow


【解决方案1】:

这是一个“正确”的方法,尽管在这个例子中有点过分了。您应该在 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> 

角度滤镜

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

【讨论】:

    猜你喜欢
    • 2023-03-04
    • 2017-09-05
    • 2016-03-07
    • 1970-01-01
    • 2020-12-22
    • 2019-05-17
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    相关资源
    最近更新 更多