AngularJS - $watch内部的初始化,取决于两个模型
AngularJS - initialization inside $watch which depends on two models
我有一个异步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);
相关文章:
- sailsjs在创建两个模型时的错误处理
- 保存两个模型(属于第三个模型)和一个提交
- 使用包含过滤器在环回中连接两个模型
- 比较主干中的两个模型属性
- 在 ng 模型中具有单向绑定的两个输入
- 为什么将子模型添加到两个父模型
- 通过Ajax在两个视图模型中重新加载数据
- 连接angularjs中的两个范围模型
- 在一个输入文本框中绑定两个模型名称
- AngularJS - $watch内部的初始化,取决于两个模型
- AngularUI:在应用过滤器的情况下正确更新两个列表之间的模型
- 我需要在两个模型(rails)之间创建一个新关系,然后通过javascript更改关系模型的属性
- Rails-从两个模型中获取json-格式化json
- 如何在两个不同的控制器中传递ng模型的值
- 如何找到两个输入的模型函数
- 如何使用AngularJs在html中定义两个模型
- 将两个模型与一个模型传递到主干比较器,并进行字母数字排序
- 在主干的一个视图中使用两个模型时出现问题
- 在knockout js中如何在两个视图模型之间交换值
- Angular -将两个输入ng模型合并为一个