[英]Watch for changes in object with form based and non-form based properties
在相當大的頁面上,用戶可以通過多種方式編輯數據:-更改某些“經典”輸入字段-通過單擊按鈕添加文件-通過拖放更改項目順序
在HTML中,一個簡化的示例可能如下所示:
<form>
Name: <input ng-model="person.name">
Title: <input ng-model="person.title">
Image: <our-custom-image-uploade-directive ng-model="person.image"/>
Skills: <our-custom-skill-drag-and-drop-directive ng-model="person.skills"/>
<button ng-click="save()">Save</button>
</form>
您會看到,有些編輯“設施”是基於表單的,有些則不是。
現在,有一個相當簡單的任務要做:如果用戶未進行任何更改或碰巧遇到的數據狀態與用戶與數據進行交互之前的狀態完全相同,則禁用“保存”按鈕。
現在我想知道哪種方法是最好的方法。
一種方法可能是深入觀察整個人對象。 像那樣:
$scope.backupCopyOfPerson = angular.copy($scope.person); // Creae a backup copy of the state before the user changed something
$scope.$watch('person', function (newValue) {
if(newValue && $scope.backupCopyOfPerson) {
if(angular.equals(newValue, $scope.backupCopyOfPerson)) {
$scope.unsavedChanges = false;
}
else {
$scope.unsavedChanges = true;
}
}
}, true);
但是,深入觀察具有許多子對象等的大對象可能會導致一些嚴重的性能問題。
另一個想法是, ng-pristine
表單字段使用ng-pristine
並在所有其他指令中執行$setDirty()
/ $setPristine()
。 那可能更快,但是絕對不是一個優雅的解決方案。
你怎么看?
角版本為1.58
我對此:
如果您對觀看性能有疑問:您應該結合進行常規輸入的角度形式檢查,並在其他屬性上添加觀看者。
這將節省您的時間和性能,因為您將觀看尚未存在的變量
$scope.$watch('person.image', function (newValue) {
$scope.unsavedChanges.image = ($scope.person.image == $scope.backupCopyOfPerson.image)
}}, true);
然后在保存時檢查您的unsavedChanges
是否至少為1 true
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.