我正在努力创建一个指令.事情根本就没有用,所以我简化了事情,直到我发现这个基本的竞争条件问题给我带来了问题.在我的指令控制器中,我需要做一些检查,比如…
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); } }; });
解决方法
请记住,在“链接”阶段(当您分配控制器时),$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; });