我目前有一个如下表格:
<form autocomplete="on" enctype="multipart/form-data" accept-charset="UTF-8" method="POST" action="{{trustSrc(SUBMIT_URL)}}">
<input type="text" name="firstinput" ng-model="first"/>
<input type="text" name="secondinput" ng-model="second"/>
<input type='submit'/>
</form>
和控制器一样:
$scope.first = "first";
$scope.second = "second";
$scope.SUBMIT_URL = DATABASE_URL + "forms/submit/";
$scope.trustSrc = function(src) {
return $sce.trustAsResourceUrl(src);
};
当我按原样提交此表单时,它对后端工作得很好。但是我现在需要使用ng-submit
代替标准HTML表单提交,因为我需要在$scope.first
中运行查找和替换。后端期望数据完全按照原始HTML表单的方式发布。如何使用$http
或$resource
以与HTML表单完全相同的格式发布?
答案 0 :(得分:0)
目前还不是很清楚你想要完成什么。但是,您应该稍微整理一下代码,以使实现更容易:
ng-click
(或ng-submit
)提交。动作将进入你的JS逻辑。 novalidate
属性,以便Angular可以正确格式化,并自行验证您的表单(并且您不会产生令人困惑的跨浏览器效果)。考虑到这些,您的新标记将是:
<form autocomplete="on" enctype="multipart/form-data" accept-charset="UTF-8" novalidate>
<input type="text" name="first" ng-model="form.first" />
<input type="text" name="second" ng-model="form.second" />
<button ng-click="submit">Submit</button>
</form>
您的JS指令是:
app.directive('form', function($http)
{
return function(scope, element, attrs)
{
// Leave this empty if you don't have an initial data set
scope.form = {
first : 'First Thing To Write',
second : 'Second item'
}
// Now submission is called
scope.submit = function()
{
// You have access to the variable scope.form
// This contains ALL of your form and is in the right format
// to be sent to an backend API call; it will be a JSON format
// Use $http or $resource to make your request now:
$http.post('/api/call', scope.form)
.success(function(response)
{
// Submission successful. Post-process the response
})
}
}
});