Angular:跟踪模型的每一次变化

Angular: tracking of every change in models

更新: 我最终使用了访问模型并调用设置器内部的外部更改跟踪的属性。

get text(): string { 
    return model.text
}
set text(value: string) {
    // <-- Call the change tracker here
    this.model.text = value;
}

原题

我有一个使用 AngularJS 编写的系统,我需要从外部跟踪每个模型的变化(跟踪脏污)。在 AngularJS 中很简单,只需为每个模型的 属性 添加 watchers(包括数组内元素属性的更改)。 注意:模型用作 UI 组件的数据。

数据流是这样的:

  1. SPA 从服务器请求数据。
  2. 服务器获取数据。
  3. 一个 watcher 在返回数据之前被添加到每个模型的 属性。
  4. 观看的模型返回到 SPA。

这是监视更改的主要代码:

public attachModel(obj : any, id : string, scope: ng.IScope, propertyName: string) {
    var idObj = obj.Id;
    this.attachedObjs[obj.Id] = obj; // Just keeping control of tracked objs
    var that = this;
    // The 'id' used in the watch is unique for the tracked property
    scope.$watch(id, function () {
        that.changeTracker(idObj, propertyName); // Calls dirty tracking
    });
}

每次在任何模型中更改 属性 时,都会触发一个事件,并且模型的 属性 在外部标记为 dirty变更控制。

我正在尝试在新的 Angular 中寻找此功能的替代品,但我觉得我的方向不对,我目前唯一的选择是:

一件重要的事情是,在 AngularJS 中,我有一个点,所有模型都被添加到脏跟踪控制中。

在Angular中有什么方法可以做到这一点吗?或者拦截 Angular 的 变化检测 以触发脏跟踪的方法?

注意: 我发现了一个问题,但我在最初的搜索中不知何故遗漏了这个问题,有没有办法在 ngForm 之外实现这个问题?

如果您要跟踪的模型是 angular 表单中的表单输入,您可以收听 valueChanges 流。