我正在努力创建一个指令。 事情根本没有用,所以我简化了事情,直到我发现这个基本的竞争条件问题给我带来了问题。 在我的指令控制器中,我需要做一些检查,比如...
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调用的时间长短而起作用。
I'm trying my hand at creating a directive. Things simply weren't working so I simplified things until I found this basic race condition issue causing problems for me. In my directive's controller I need to do some checks like...
if ($scope.test.someValue === true) { $scope.test.anotherValue += 1; }Here's my basic directive with some logs to illustrate how this issue manifests.
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); } }; });What is the correct way to work with this race condition? I'm worried that in the real world this timeout function is going to work or fail based on how long an api call takes.
最满意答案
请记住,在“链接”阶段(当您分配控制器时), $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; });Remember that at the "link" phase (when you assign your controller), the $scope.test variable has not been assigned yet - hence the undefined
The $timeout(fn, timeout) is a way to execute something which will affect something in the $scope. You can set your $timeout() value to 0 and it will still work. The reason for this is because the $timeout(...) function will be deferred till after the current $digest() cycle.
References: $timeout() $digest()
Additionally, if you want to watch for changes in a particular value you can do:
$scope.$watch("test.somevalue", function(new_val, old_val) { console.log("somevalue changed!! - increment othervalue"); $scope.othervalue += 1; });更多推荐
发布评论