如何以角度1.5重置表单

时间:2018-02-18 10:53:52

标签: javascript angularjs forms

我有这个标记

如何在相应的组件中重置它?

<form name="voiceForm" novalidate>...</form>

我试过了:

this.voiceForm.$setPristine();
self.voiceForm.reset();

但是没有定义错误voiceForm

这是我的组成部分:

(function (app) {
    app.component('voiceFormComponent', {
        templateUrl: 'partials/voice-form.html',
        controller: ['$scope', '$state', '$stateParams',
            function ($scope, $state, $stateParams) {

                var self = this;

                console.log("in voice prompt component");

                self.addVoice = function () {
                     self.voiceForm.$setPristine();
                     $state.go("add");
                }

3 个答案:

答案 0 :(得分:1)

您可以传递表单并致电 setPristine

&#13;
&#13;
var app = angular.module('formReset', []);

app.controller('MainCtrl', function() {
this.data = {
name: ''
};

this.reset = function(form) {
this.data.name = '';
form.$setPristine();
};

});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app="formReset">

<head>
<title>form.$submitted</title>
<script src="http://code.angularjs.org/1.3.2/angular.min.js"></script>
<script src="app.js"></script>
</head>

<body>
<div ng-controller="MainCtrl as ctrl">
 <form name="form" novalidate>
  <input name="name" ng-model="ctrl.data.name" placeholder="Name" required   />
  <input type="submit" />
  <button type="button" class="button" ng-click="ctrl.reset(form)">Reset</button>
</form>

<pre>

 Submitted: {{form.$submitted}}

</pre>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <form name="myfrom">
      <input type="text" ng-model="data.name">
      <input type="text" ng-model="data.phone">
      <input type="text" ng-model="data.city">
      <input type="button" ng-click="reset_from()" value="reset">
    </form>
    {{data}}
  </body>

</html>

<script>
var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  $scope.data = {name:"Sahed sawon",phone:"8801714999720",city:"Dhaka"};
  $scope.reset_from = function() {
    $scope.data = {};
  }
});

</script>

答案 2 :(得分:0)

当我在表单中有一个表单(这是不允许的)时,我遇到了类似的问题,而修复是使用ng-form代替子表单。也许试试ng-form