我正在尝试检测我的应用程序是否有更改,并在保存之前提示用户保存。我正在使用角度的$ watch功能。我发现当我重置我正在观看的字段时,即使我重置了已更改的标志,它也无法正常工作。这是竞争条件吗?
这是插件 - 注意Save可以工作,但在按下New后,它仍然显示有未保存的更改。
http://plnkr.co/edit/0EQpCarjVj5o2cb8TeNa?p=preview
JS:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.changed = false;
$scope.$watch('[thing]', function(newValue, oldValue) {
if (newValue != oldValue) {
$scope.changed = true;
}
}, true);
$scope.saveClicked = function() {
// save the data somewhere
$scope.changed = false; // this works!
};
$scope.newClicked = function() {
$scope.thing = {};
$scope.changed = false; // this doesn't work!
};
});
HTML:
<body ng-controller="MainCtrl">
<form id=f>
<input type=text name=t1 ng-model=thing.t1>
<input type=text name=t2 ng-model=thing.t2>
<button ng-click="saveClicked()">Save</button>
<button ng-click="newClicked()">New</button>
</form>
<br>
<span ng-show="changed">You have unsaved changes!</span>
<span ng-show="!changed">All changes have been saved.</span>
</body>
答案 0 :(得分:1)
问题在于,由于$watch
的工作原理,这实际上是在 $scope.changed = false
之后运行所以最终会再次设置为true。
有几种可能的解决方案,但其中一种方法是检查默认条件。例如:
$scope.changed = false;
$scope.thing = null;
$scope.$watch('thing', function(newValue, oldValue) {
// Default value means the form is now clean
if (newValue == null) {
return;
// Also set to null when `New` is clicked.