我需要一些建议,如何正确地重置一个形式在角JS。我的表单数据被推送到一个名为.services的对象中,但是每次我点击submit时,我都希望该表单(文本输入和复选框)被重置。
我的表格是这样的:
<div ng-app="app">
<div ng-controller="MainCtrl">
<form role="form" ng-submit="createService(newService)">
<div class="form-group">
<label for="serviceName">Name of Service</label>
<input id="serviceName" type="text" ng-model="newService.name">
</div>
<label ng-repeat="sector in sectors" for="{{sector}}">
<input type="checkbox" id="{{sector}}" value="{{sector}}" ng-model="newService.sectors[sector]">{{sector}}</label>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<section class="row well live-preview" ng-repeat="service in services">
<h3><a href="/">{{service.name}}</a></h3>
<ul class="list-unstyled">
<li ng-repeat="(sector, state) in service.sectors"> <span class="label label-primary" ng-show="state">{{sector}}</span>
</li>
</ul>
</section>
</div>
</div>我的JS:
angular.module('app', [])
.controller('MainCtrl', function ($scope) {
$scope.sectors = ['health', 'social', 'education'];
$scope.services = [{
'name': 'Hernia Repair',
'sectors': {
'health': true
}
}, {
'name': 'Cancers',
'sectors': {
'health': true,
'social': true,
'education': true
}
}];
function createService(service) {
$scope.services.push(service);
}
$scope.createService = createService;
});我尝试创建一个resetForm()函数,该函数将name和sector设置为空字符串,但随后出现了一些奇怪的问题,在这些问题中,提交的复选框的值没有被正确设置。
对此的任何帮助都将不胜感激。
提前谢谢。
更新:
像这样的东西有用吗?
function resetForm() {
$scope.newService = {
name: '',
sector: {}
};
}发布于 2014-10-16 08:22:55
您是否尝试过给表单命名,然后调用$setPristine()?
然后调用$scope.serviceForm.$setPristine();
发布于 2014-10-15 01:06:40
你为什么要把它设置为空字符串?将新服务设置为空对象。您正在使用ng模型,它应该能够为您设置键和值。除非您想要复选框的默认值,在该复选框中,可以将其设置为具有默认值的对象。
https://stackoverflow.com/questions/26372791
复制相似问题