gpt4 book ai didi

angularjs - 如何在没有超时功能的情况下克服指令中的竞争条件?

转载 作者:行者123 更新时间:2023-12-03 08:17:25 26 4
gpt4 key购买 nike

我正在尝试创建指令。事情根本不起作用,所以我简化了事情,直到我发现这个基本的竞争条件问题给我带来了问题。在我的指令的 Controller 中,我需要做一些检查,比如......

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 调用需要多长时间来工作或失败。

最佳答案

请记住,在“链接”阶段(分配 Controller 时),$scope.test变量尚未分配 - 因此 undefined$timeout(fn, timeout)是一种执行某些会影响 $scope 中某些内容的方法。您可以将 $timeout() 值设置为 0,它仍然可以工作。这是因为 $timeout(...) 函数将被推迟到当前 $digest() 之后。循环。

引用文献:
$timeout()
$digest()

此外,如果您想观察特定值的变化,您可以执行以下操作:

$scope.$watch("test.somevalue", function(new_val, old_val) {
console.log("somevalue changed!! - increment othervalue");
$scope.othervalue += 1;
});

关于angularjs - 如何在没有超时功能的情况下克服指令中的竞争条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23848127/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com