我如何得到ng-if重申阵列?

时间:2015-06-25 14:43:17

标签: angular

我有一个*ng-for的元素。它完美地呈现数据(对象数组)。如果我添加一个元素,那么我会在视图中看到新数据。

<div *ng-for="#item of items" [attr.bob]="item.bob" />

如果我修改了项目列表中的项目,我需要将其反映在我的视图中,但事实并非如此。我怎样才能做到这一点?我可以触发整个数组的完整渲染 - 我可以通过添加/删除元素 - 但这里最好的做法是什么?也许有一种方法可以“弄脏”#item?

编辑:我将我的代码更改回原来的版本,我无法开始工作,因为我发布的版本确实有效,无效这个问题。 我仍然很好奇你是否可以手动强制重复迭代尽管如此我还是要离开这个问题。如果你在这里寻找解决方案,我所做的是直接依赖于属性(索引),而不是嵌套在数组中的对象内。

2 个答案:

答案 0 :(得分:2)

No need of the re-iterations actually. Attribute is binded to the element of the array and will change respectively. The change of the array also will be displayed automatically.

function RandomColorHex(){
  return '#'+Math.floor(Math.random()*16777215).toString(16);
}

@Component({
    selector: 'app'
})
@View({
  template: `
    <button (click)="push()">add item</button>
    <p *ng-for="#item of items" [style.color]="item.color">{{ item.title }}</p>
  `,
  directives: [NgFor]
})
class AppComponent{
  constructor(){
    this.items = [
      {title:"foo", color:"red"},
      {title:"bar", color:"green"},
      {title:"baz", color:"blue"}
    ];

    setInterval(() => {
      let randomElement = this.items[Math.floor(Math.random()*this.items.length)];
      randomElement.color = RandomColorHex();
    }, 500);
  }
  push(){
    this.items.push({title:"i'm new here", color:"black"});
  }
}

Live example

答案 1 :(得分:1)

你不能在某处强制设置[attr.something]的值吗?

相关问题