我有几个表单可以与后端服务交互以保存数据。
我想知道是否有一种标准的 Angular 方法来检测模型的哪些属性已更改并仅在 POST 中发送它们?当前,所有事件都在未更改时发送。
最佳答案
根据问题,可能有两种情况。
一旦用户填写了字段并单击“保存”按钮,该按钮最终将发送一个用于保存//更新值的 PATCH 请求。
当用户更改值时,需要发出请求。
对于 1.
您可以通过维护 HashMap 来跟踪更改的内容。对所有用户输入字段使用 ng-modal
指令。
假设有两个输入字段 i。 用户名
和密码
。
<input type="text" ng-modal="username" />
<input type="password" ng-modal="password" />
在你的 Controller 中
$scope.userInfo = {
user: $scope.username,
pass: $scope.password
};
现在,如果有任何更改,它将通过双向绑定(bind)反射(reflect)在您的 View 和模型中。
因此,现在您可以比较旧值和新值并相应地发送所需的值。
对于 2.
使用 Angular 的 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
关于javascript - 如何发送已更改的 Angular 形式数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32021368/