2015-08-15 37 views
1

我有一些與後端服務交互的表單來保存數據。如何發送已更改的角度表單數據?

我想知道是否有一個標準的角度方式來檢測模型已更改併發送它們只在POST中的哪些屬性?目前全部發送事件時沒有改變。

+0

角度沒有任何建設,爲你問 – harishr

+0

我猜你的形式是非常大,還有一個原因,發送的所有數據是不可選的。在這種情況下,您必須編寫自己的邏輯來確定發生了什麼變化,並且只發送POST中已更改的數據。 –

+0

您應該有一個最終對象發送,比如'$ scope.final_data',並在您的表單中你應該使用一些指令,比如'ng-change',每當你改變一個模型時,將它添加到'final_data'中。 –

回答

3

根據這個問題,可以有兩種情況。

  1. 一旦用戶填寫了字段並單擊SAVE按鈕,SAVE按鈕將最終發送PATCH請求以保存//更新值。

  2. 當用戶更改值時,需要進行請求。

爲1

你可以保持一個什麼樣的通過保持一個HashMap得到改變軌道。對所有用戶輸入字段使用ng-modal指令。 我們假設有兩個輸入字段i。 usernamepassword

<input type="text" ng-modal="username" /> 
<input type="password" ng-modal="password" /> 

在你的控制器

$scope.userInfo = { 
    user: $scope.username, 
    pass: $scope.password 
}; 

現在,如果有的話得到改變,這將反映在通過雙向綁定您的視圖和模型。

因此,現在您可以比較舊值和新值,並據此發送所需值。

爲2

使用角的watchCollection

scope.$watchCollection('[username, password]', function() { 
    // send a request 
}); 

編輯

一個可以使用第二種方法去抖方法

// Returns a function, that, as long as it continues to be invoked, will not 
// be triggered. The function will be called after it stops being called for 
// N milliseconds. If `immediate` is passed, trigger the function on the 
// leading edge, instead of the trailing. 
_.debounce = function(func, wait, immediate) { 
    var timeout, args, context, timestamp, result; 

    var later = function() { 
    var last = _.now() - timestamp; 

    if (last < wait && last >= 0) { 
     timeout = setTimeout(later, wait - last); 
    } else { 
     timeout = null; 
     if (!immediate) { 
     result = func.apply(context, args); 
     if (!timeout) context = args = null; 
     } 
    } 
    }; 

    return function() { 
    context = this; 
    args = arguments; 
    timestamp = _.now(); 
    var callNow = immediate && !timeout; 
    if (!timeout) timeout = setTimeout(later, wait); 
    if (callNow) { 
     result = func.apply(context, args); 
     context = args = null; 
    } 

    return result; 
    }; 
}; 

來源:https://github.com/jashkenas/underscore/blob/master/underscore.js

1

沒有標準的方式。這是另一種無法看守的方法。您可以將「表單」作爲更新的參數傳遞,並使用「表單」來標識哪些控件已變髒。

http://plnkr.co/edit/8Og1m8eM54eOzKMDJtfJ?p=preview

.controller('ExampleController', ['$scope', function($scope) { 
    $scope.user = {} 
    var formFields = ['firstName', 'lastName']; 

    $scope.update = function(form, user) { 
    $scope.updatedFields = {}; 
    angular.forEach(formFields, function(field) { 
     if (form[field].$dirty) { 
     $scope.updatedFields[field] = $scope.user[field]; 
     //Temporarily set the field back to pristine. 
     //This is only for demo 
     form[field].$dirty = false; 
     } 
    }); 
    }; 
}]); 

你可以使用輸入名稱和型號相同的字符串。

<input type="text" ng-model="user.firstName" name="firstName"/>