【发布时间】:2016-05-05 19:12:01
【问题描述】:
提交后,我的表单显示为脏,带有红色边框且没有提交文本。我尝试将 .$setPristine 和/或 .$setUntouched 的各种组合添加到 app.js 的第 34 行,并返回绿色边框,提交文本仍然存在。
我读过有关使用 $scopes 的文章。不确定是否需要,我不熟悉它们。
app.js
* the page hello-world auto-reloads the preview on the right c9 panel */
/* global angular */ /* angular is defined in html document as a src'ed js file. linter says to declare as a global in a comment here */
(function(){
// variables are declared at the top of the function's scope
// three default entries to start with
var entries = [{
title: 'Title1',
body: 'This is a test, 1.',
createdOn: 1397490980837
}, {
title: 'Title2',
body: 'This is a test, 2.',
createdOn: 1397490980837
}, {
title: 'Title3',
body: 'This is a test, 3.',
createdOn: 1397490980837
}];
var app = angular.module('blogPosts', []);
app.controller('EntriesController', function(){
// `this` entry, the current entry for this method, is defaulted to an empty object
this.entry = {};
this.entries = entries;
// method is called when adding an entry
this.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
this.entry.$setPristine();
this.entry = {};
//this.entry.$setPristine = {};
//this.entry.$clearForm = {};
};
});
})();
index.html
<!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>
CSS
.ng-invalid.ng-dirty {
border-color: red;
}
.ng-valid.ng-dirty {
border-color: green;
}
【问题讨论】:
-
您需要在表单元素上使用 $setPristine