我想在我的整个表单上使用$ scope。$ watch并检测更改,然后显示警告“数据已更改。请保存”。问题是我只想在从服务器获取数据时传递oldValue。
$http({
method: "post",
url: "url",
data: {
Pages: {
id: pageId
}
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function(data) {
$scope.data = data.editedPage.jkOutputContainer.editedPage.pagesObject;
$scope.$watch('data',function(newValue, oldValue) {
if(newValue != oldValue) {
$scope.dataHasChanged = true;
} else {
$scope.dataHasChanged = false;
}
}, true);
});
我可以在表单中的每个输入上使用ng-init和ng-change,但我想在表单上使用$ scope。$ watch。
编辑:简而言之,我希望在用户将其更改恢复到从服务器获取的状态时隐藏警报。
答案 0 :(得分:0)
要解决您的问题,请不要将服务器的响应绑定到$scope
变量,而只是将其分配给脚本中引用的变量。这是一个例子。
$http({
method: "post",
url: "url",
data: {
Pages: {
id: pageId
}
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function(data) {
// To solve your problem, just store the server data in a variable.
var fromServer = data.editedPage.jkOutputContainer.editedPage.pagesObject;
$scope.data = fromServer; //<- Reference the var here.
$scope.$watch('data',function(newValue, oldValue) {
if(newValue != fromServer) { //<- Reference the var here.
$scope.dataHasChanged = true;
} else {
$scope.dataHasChanged = false;
}
}, true);
});
希望这很有用!
答案 1 :(得分:0)
$scope.watch('[formname]', checkChanged, true)
function checkChanged(newVal) {
if (!angular.equals(newVal,$scope.data)) warnUser()
}
^这将观察表单中的每个表达式并提醒用户