首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AngularJS中的重置形式

AngularJS中的重置形式
EN

Stack Overflow用户
提问于 2014-10-15 00:56:57
回答 2查看 302关注 0票数 0

我需要一些建议,如何正确地重置一个形式在角JS。我的表单数据被推送到一个名为.services的对象中,但是每次我点击submit时,我都希望该表单(文本输入和复选框)被重置。

我的表格是这样的:

代码语言:javascript
复制
<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:

代码语言:javascript
复制
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()函数,该函数将namesector设置为空字符串,但随后出现了一些奇怪的问题,在这些问题中,提交的复选框的值没有被正确设置。

对此的任何帮助都将不胜感激。

提前谢谢。

更新:

像这样的东西有用吗?

代码语言:javascript
复制
function resetForm() {
    $scope.newService = {
        name: '',
        sector: {}
    };
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-10-16 08:22:55

您是否尝试过给表单命名,然后调用$setPristine()?

然后调用$scope.serviceForm.$setPristine();

票数 1
EN

Stack Overflow用户

发布于 2014-10-15 01:06:40

你为什么要把它设置为空字符串?将新服务设置为空对象。您正在使用ng模型,它应该能够为您设置键和值。除非您想要复选框的默认值,在该复选框中,可以将其设置为具有默认值的对象。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26372791

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档