Angular 绑定(bind)到函数结果

标签 angular watch angularjs-digest

我一直在浏览 angular.io 上的指南并发现 the section on the NgClass directive 。 在提供的示例中,ngClass 的源是一个组件函数:

// HTML
<div [ngClass]="setClasses()">This div is saveable and special</div>

// Controller
setClasses() {
  let classes =  {
    saveable: this.canSave,      // true
    modified: !this.isUnchanged, // false
    special: this.isSpecial,     // true
  };
  return classes;
}

考虑到,这不会在摘要周期中产生很大的开销吗? 该指令不知道函数的结果何时改变并且 会在每个摘要周期内触发函数的新评估吗?在 对比我希望下面的代码能够提供相同的功能 但仅当观测值之一发生变化时才进行专门重新评估 已更改(canSave、isUnchanged、isSpecial)。

<div [ngClass]="{ saveable : canSave, modified : !isUnchanged, special: isSpecial }">This div is saveable and special</div>

有人可以告诉我我应该考虑什么吗 优化性能?一个示例用例是将此 ngClass 打开 ngRepeat 在可见页面上创建约 200 个元素。

作为一个侧面节点和较小的问题,我想知道是否有什么好的 了解一次性绑定(bind)的资源(在 Angular2 与 Angular1 中)。这 指南似乎没有涵盖这一点,我希望有一个异步的 时间绑定(bind)在 angular2 中可用。

最佳答案

Does this not create a large overhead during the digest cycle considering the directive does not know when the result of the function has changed and would trigger a new evaluation of the function during each digest cycle? In contrast I'd expect the following code to provide the same functionality but to only re-evaluate specifically when one of the observed values have changed (canSave, isUnchanged, isSpecial).

你的结论是正确的。

setClasses 方法为每次调用返回一个不同的实例,这使得 ngClass 中的比较更加昂贵。如果只要没有更改依赖关系就返回相同的实例,则绑定(bind)到方法 this 方式很好。

这个问题最近得到了解决。 https://github.com/angular/angular.io/issues/3072

As a side node and smaller question I was wondering if there is any good resource to learn about one-time binding (in angular2 vs angular1). The guide does not appear to cover this and I was hoping to have an async one time bind available in angular2.

Angular2 不支持一次性绑定(bind)。

关于 Angular 绑定(bind)到函数结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41550175/

相关文章:

angular - SSR with (RE)Hydration in Angular

swift - 如果没有 iphone 的默认 watch 应用程序或苹果 watch 本身,是否可以为苹果 watch 生成 .watchface?

akka - 在 Akka 中,如果我 watch() 一个死的 ActorRef 会发生什么?

javascript - "Ghost"ng点击功能

javascript - 为什么 Angular Digest Cycle 没有被调用?

javascript - Angular 模型变量在 DOM 更新之前更新过早,导致 UI 为 "behind"?

javascript - 从 Angular 1 移动到 Angular 2 时所需的先决条件

javascript - 在 Angular 2 中导入 Socket.io 客户端,出现依赖项错误

angular - 类型 'map' 上不存在属性 'Observable<Blob>'

JavaScript 属性更改事件