AngularJS - $watch内部的初始化,取决于两个模型

AngularJS - initialization inside $watch which depends on two models

本文关键字:模型 两个 取决于 watch 内部 初始化 AngularJS      更新时间:2023-09-26

我有一个异步JS函数(即http请求,但是一个请求,这是通过Java绑定直接调用我的JavaFX应用程序),它返回一些结果并将其放入模型属性中,modelAttribute1

我在其他一些模型modelAttribute2上还有一个$watch函数,它使用第一个模型,即:

scope.$watch(modelAttribute2, function(newVal, oldVal){
    scope.$apply(function(){
        // newVal is correct, but modelAttribute1 is not yet initialized!
        scope.scriptText = loadFile(newVal, scope[modelAttribute1]); 
    });
});

问题是在我从 Java 获得结果之前,正在执行此监视表达式。

那么有没有一种方法可以做到这一点,比如创建一个承诺并倾听它的计算来完成?

一个有承诺的解决方案:

var d1 = $q.defer(), d2 = $q.defer();
scope.$watch("modelAttribute1", function(newVal) {
    if( newVal != null ) d1.resolve(newVal);
});
scope.$watch("modelAttribute2", function(newVal) {
    if( newVal != null ) d2.resolve(newVal);
});
$q.all([d1, d2]).then(function(arr) {
    // here scope.modelAttribute1 = arr[0],
    //      scope.modelAttribute2 = arr[1]
    scope.scriptText = loadFile(arr[1], arr[0]);
});

由于 http 请求是异步的,我们可以用这样的承诺来包装它:

   var data = //...<from http>
   var deferred = $q.defer();
   deferred.resolve(data);
   deferred.then(function(arr) {   
      modelAttribute1 = arr;
    });

作为旁注

不知道你是否使用深度监视,设置标志true

scope.$watch(modelAttribute2, function(newVal, oldVal){
    scope.$apply(function(){
        // newVal is correct, but modelAttribute1 is not yet initialized!
        scope.scriptText = loadFile(newVal, scope[modelAttribute1]); 
    });
}, true);