2015-08-15 38 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"/>