angularjs – 如何在没有超时功能的情况下克服指令中的竞争条件
发布时间:2020-12-17 17:18:59 所属栏目:安全 来源:网络整理
导读:我正在努力创建一个指令.事情根本就没有用,所以我简化了事情,直到我发现这个基本的竞争条件问题给我带来了问题.在我的指令控制器中,我需要做一些检查,比如… if ($scope.test.someValue === true) { $scope.test.anotherValue += 1; } 这是我的基本指令,其中
|
我正在努力创建一个指令.事情根本就没有用,所以我简化了事情,直到我发现这个基本的竞争条件问题给我带来了问题.在我的指令控制器中,我需要做一些检查,比如…
if ($scope.test.someValue === true) { $scope.test.anotherValue += 1; }
这是我的基本指令,其中包含一些日志以说明此问题是如何显示的. app.directive('myDirective',function () {
return {
restrict: 'E',replace: true,scope: {
test: '='
},template: '<div><pre>{{ test | json }}</pre></div>',controller: function ($scope,$timeout) {
// this logs undefined
console.log($scope.test);
// this logs the scope bound 'test' object
$timeout(function() {
console.log($scope.test);
},300);
}
};
});
使用这种竞争条件的正确方法是什么?我担心在现实世界中,这个超时功能会根据api调用的时间长短而起作用. 解决方法
请记住,在“链接”阶段(当您分配控制器时),$scope.test变量尚未分配 – 因此未定义
$timeout(fn,timeout)是一种执行会影响$scope内容的方法.您可以将$timeout()值设置为0,它仍然可以工作.这是因为$timeout(…)函数将延迟到当前$digest()循环之后. 参考文献: 此外,如果您想要查看特定值的更改,您可以执行以下操作: $scope.$watch("test.somevalue",function(new_val,old_val) {
console.log("somevalue changed!! - increment othervalue");
$scope.othervalue += 1;
});
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
