Angular: ng-repeat 取决于其他对象的状态

Angular: ng-repeat depending on state of other object

我无法弄清楚如何根据不同数组中对象的状态使用 ng-repeat。

假设我的页面显示 3 tables,使用 ng-repeat 填充:

  1. 人员列表,带有基于 active 字段选中的复选框。
  2. 消息列表,仅显示具有 active : true 的人的消息。
  3. 关于从第二个 table 聚合的消息的统计信息列表,显示每个类别中的消息数量,但应该只计算具有 active : true 状态的用户的消息。

示例如下。第一个 table 显示所有用户,未选中 'anna' 的复选框。第二个带有消息的 table 不显示 'anna' 的消息。第三个 table 显示每个类别中的消息数,发送给除安娜以外的任何人的消息。

$scope.person = [ 
    { id : 1, name : "john", active : true},
    { id : 2, name : "bob", active: true},
    { id : 3, name : "anna", active: false}
]

$scope.messages = [
    { personid: 1, message: "hello", category: "greeting"},
    { personid: 1, message: "hi", category: "greeting"},
    { personid: 2, message: "hello", category: "greeting"},
    { personid: 2, message: "no", category: "denial"},
    { personid: 2, message: "yes", category: "confirmation"},
    { personid: 3, message: "yes", category: "confirmation"}
]

$scope.messagestatistics = [
    { category : "greeting", count : 3},
    { category : "denial", count: 1},
    { category : "confirmation", count: 1}
]

上面显示的 messagestatistics 数组是在仅考虑人 'john' 和 'anna' 的情况下生成的。

我已经能够使用 ng-repeat 创建第一个 table,并根据用户单击的复选框更新 active 字段。我如何将其传播到其他 tables?

到目前为止,我已经尝试过为消息数组中的每个对象添加一个状态,即根据人员数组的状态表示 active : true/false。然后,每次用户单击第一个 table 中的复选框时,我都会更新此状态,并重新生成消息统计信息 table。但是,我会在状态字段中保留重复数据,并希望有更多 angular-y 方法来做到这一点?我还担心如果我有 10 000 条消息,这可能不是一个好方法?

所以您的问题主要是如何根据某些外部输入重复过滤值?一种方法就是这样做,filter! Angular 中的标准过滤器采用一个数组并仅过滤掉那些匹配比较器函数的条目。你会做这样的事情:

<div ng-repeat="message in messages | filter:isActive">
  <span>{{message.message}}</span>
</div>

在这种情况下,isActive 是您在控制器中定义的任意方法,它接受一个对象(消息)和 returns true 或 false,具体取决于它是否应该显示与否。需要注意的一件事是,过滤器是 运行 数组中的每个项目一次,并且它可以在每个摘要周期中被触发多次,因此请保持轻量级。

例如,不要启动循环数组来检查过滤器内的活动标志。在过滤器 外部 编译活跃用户列表,然后在过滤器内部编译,以便对该列表进行简单检查。

Here is a fiddle with a simple example。最后的统计部分留作 reader :)

的练习