Angular - alert()在视图更改之前执行

时间:2017-05-17 01:01:25

标签: javascript angularjs controller

为什么在视图更改之前执行alert()?如何改变视图,然后然后警告会弹出?

var app = angular.module("myApp", []);

app.controller("myCtrl", function($scope) {
  $scope.points = 0;
  $scope.add = function() {
    ++$scope.points;
    alert('This alert appears before the score is changed in the view')
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <p ng-click="add()">
    Score: {{ points }}
  </p>
</div>

2 个答案:

答案 0 :(得分:1)

这是基于浏览器的工作原理。只有在事件结束但数据已经更改后,视图才会rerender

参考以下我完全复制的示例,除了我添加一行console.log。您可以通过打开的浏览器控制台确认发生了什么。

&#13;
&#13;
var app = angular.module("myApp", []);

app.controller("myCtrl", function($scope) {
  $scope.points = 0;
  $scope.add = function() {
    ++$scope.points;
    console.log($scope.points);    // open browser to confirm
    alert('This alert appears before the score is changed in the view')
  };
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <p ng-click="add()">
    Score: {{ points }}
  </p>
</div>
&#13;
&#13;
&#13;

没有angularjs的正常情况

&#13;
&#13;
function showAlert() {
  document.getElementById("show").innerHTML = '1111';
  alert('Information changed');
}
&#13;
<span id="show"></span>
<input type="text" onchange="showAlert()">
&#13;
&#13;
&#13;

我使用$timeout

评论的棘手例子

&#13;
&#13;
var app = angular.module("myApp", []);

app.controller("myCtrl", function($scope, $timeout) {
  $scope.points = 0;
  $scope.add = function() {
    ++$scope.points;
    console.log($scope.points);    // open browser to confirm
    
    $timeout(function() {
      alert('This alert appears before the score is changed in the view');
    });
  };
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <p ng-click="add()">
    Score: {{ points }}
  </p>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

问题是在转移到digest代码之前alert()周期尚未完成。一种选择是将您的alert包裹在超时

 setTimeout(function() {
     alert('This alert appears before the score is changed in the view')
 },1);

&#13;
&#13;
var app = angular.module("myApp", []);

app.controller("myCtrl", function($scope) {
  $scope.points = 0;
  $scope.add = function() {
    ++$scope.points;
    setTimeout(function() {
     alert('This alert appears before the score is changed in the view')
    },1);
  };
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <p ng-click="add()">
    Score: {{ points }}
  </p>
</div>
&#13;
&#13;
&#13;