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

前端之家收集整理的这篇文章主要介绍了angularjs – 如何在没有超时功能的情况下克服指令中的竞争条件?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在努力创建一个指令.事情根本就没有用,所以我简化了事情,直到我发现这个基本的竞争条件问题给我带来了问题.在我的指令控制器中,我需要做一些检查,比如…

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()循环之后.

参考文献:
$timeout()
$digest()

此外,如果您想要查看特定值的更改,您可以执行以下操作:

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

猜你在找的Angularjs相关文章