2 种方式绑定在 angular 的 setTimeout 回调中不起作用 1

2 way binding not working in setTimeout callback in angular 1

我想在保存期间禁用提交按钮并在保存后启用它。

它没有启用。我可以看到旗帜发生了变化。但是 view 上的标志没有像我想象的那样更新 2 方式绑定应该给我那个。

代码如下

$scope.save = function (){
    $scope.saving_survey = true;
    setTimeout(function(){
        $scope.saving_survey = false;
        console.log($scope.saving_survey);
    }, 1000);

}


<button class="btn btn-success" ng-click="save()" ng-disabled="saving_survey">
    save {{saving_survey}}
</button>

尝试使用 $timeout 服务。它应该被注入控制器

 $scope.save = function (){
  $scope.saving_survey = true;
   $timeout(function(){
    $scope.saving_survey = false;
    console.log($scope.saving_survey);
  }, 1000);
}

基本上默认的 javascript 函数(setTimeout、interval、eventListener 等)没有 $watch 包装器。所以你需要手动触发 $watch,为此你需要调用 $scope.$apply()。调用 $apply 的最佳方式如下所示,

if(!$scope.$$phase) {
    $scope.$apply();
}

Note: $$phase return true if already digest cycle in progress else it will be false