Angularjs 1.4.7 - 在提交后清除并将形式设置为原始状态

时间:2016-05-05 19:12:02

标签: angularjs forms

提交后,我的表单显示为脏,带有红色边框,没有提交文本。我已经尝试将。$ setPristine和/或。$ setUntouched的各种组合添加到app.js中的第34行,并返回绿色边框,提交文本仍然存在。

我已阅读过有关使用$ scopes的文章。不确定是否需要,我不熟悉它们。

app.js

<!DOCTYPE html>
<html ng-app="blogPosts">
  <head>
    <link rel="stylesheet" type="text/css" href="style.css" /><!-- load Bootstrap -->
    <link rel="stylesheet" type="text/css" href="https://bootswatch.com/united/bootstrap.min.css" /><!-- load Bootstrap -->
  <script src="angular.js"></script><!-- load angular -->
  <script type="text/javascript" src="app.js"></script>
  </head>

  <body ng-controller="EntriesController as entryCtrl">

    <div ng-repeat="entry in entryCtrl.entries">
      <h3>{{entry.title}}</h3><cite class="clearfix">{{this.entry.createdOn | date}}</cite><br>
      {{entry.body}}
    </div>

      <!--  Entry Form -->
      <form name="entryForm"  
      ng-submit="entryForm.$valid &&entryCtrl.addEntry(entry)" 
      noValidate>

        <!--  Live Preview -->
        <blockquote>
          <h3>{{entryCtrl.entry.title}}</h3><br>
          {{entryCtrl.entry.body}}      
          <cite class="clearfix">{{this.entry.createdOn | date}}</cite>
        </blockquote>

      <!--  Entry Form -->
        <h4>Submit an Entry</h4>
        <fieldset class="form-group">
          <input type="title" class="form-control" placeholder="Title" title="Title" ng-model="entryCtrl.entry.title"  required/>
        </fieldset>
        <fieldset class="form-group">
          <textarea class="form-control" placeholder="Write your entry.." title="Entry" ng-model="entryCtrl.entry.body" required></textarea>
        </fieldset>
        <fieldset class="form-group">
           <input type="submit" class="btn btn-primary pull-right" value="Submit Entry" />
        </fieldset>
      </form>

  </body>

</html>

的index.html

.ng-invalid.ng-dirty {
  border-color: red;
}

.ng-valid.ng-dirty {
  border-color: green;
}

CSS

expire_fragment('my-key')

2 个答案:

答案 0 :(得分:0)

来自Reddit / u / mcassagnes

{{1}}

作品!

答案 1 :(得分:0)

是的,你的this.addEntry并没有绑定词汇。基本上失去了它的约束力。最好将其分配给主控制器定义中的变量。像这样在控制器中抽象这个。请注意,您必须更改您希望使用此语法的方式。在你看来它是EntriesController作为vm,而不是变量本身就是vm.variable。这是一个style guide来帮助巩固我的意思。希望这有助于您的未来。

  app.controller('EntriesController', function() {
    // `this` entry, the current entry for this method, is defaulted to an empty object
    var vm = this;
    vm.entry = {};
    vm.entries = entries;

    // method is called when adding an entry
    vm.addEntry = function() {
      // does this.entry exist here? good way to find out is with `console.log(this.entry);` or `debugger;`
      this.entry.createdOn = Date.now();
      entries.push(this.entry);
      console.log("entries", entries);
      // reset `this.entry` back to an empty object
      vm.entry.$setPristine();
      vm.entry = {};
      //this.entry.$setPristine = {};
      //this.entry.$clearForm = {};
    };
  });