我有一个这样的控制器:
(function() {
'use strict';
angular
.module('app.bookmark')
.controller('BookmarkEdit', BookmarkEdit);
function BookmarkEdit(BookmarkService, $stateParams, $state) {
var vm = this;
vm.bookmark = {};
vm.save = save;
function save() {
BookmarkService.insert(vm.bookmark).success(saveOk).error(saveFail);
}
/* Callbacks */
// I ommited the saveOk method!
function saveFail(data, status, headers, config){
switch(status){
case 401: console.log('401');
break;
case 422: console.log('422');
angular.forEach(data, function(value, key){
// THE CODE SHOULD COME HERE
});
break;
}
}
}})();
我的服务是这样的:
(function() {
'use strict';
angular
.module('app.bookmark')
.factory('BookmarkService', BookmarkService);
function BookmarkService($http){
var url = 'api/bookmark';
BookmarkService.insert = function(bookmark){
return $http.post(url, bookmark);
};
return BookmarkService;
}})();
如果我发送一个空表单,我的 REST 服务会进行验证并返回 (RESPONSE) 一个 JSON,如下所示:
[
{property:description, message:required}
{property:link, message:maxlength}
]
我想知道如何在各个字段下方显示这些消息?
下面是我的 HTML 代码:
<form name="bookmarkForm class="well" role="form">
<div class="form-group">
<label>ID: </label>
<span id="id-text" class="form-control-static">{{bookmark.bookmark.id}}</span>
</div>
<div class="form-group">
<label for="description">Description</label>
<input id="description" type="text" class="form-control" ng-model="bookmark.bookmark.description" value="{{bookmark.bookmark.description}}">
<div id="description-message" class="label label-danger"><!-- the message should come here if exists --></div>
</div>
<div class="form-group">
<label for="link">Link</label>
<input id="link" type="text" class="form-control" ng-model="bookmark.bookmark.link" value="{{bookmark.bookmark.link}}">
<div id="link-message" class="label label-danger"><!-- the message should come here if exists --></div>
</div>
<div class="form-group">
<button id="save" class="btn btn-primary" ng-click="bookmark.save()">Save</button>
</div>
</form>
编辑
寻找 ngMessages,我将 DIV 的消息更改为:
<div class="label label-danger" ng-messages="bookmarkForm.description.$error">
<div ng-messages-include="templates/messages.html"></div>
</div>
messages.html 文件是这样的:
<p ng-message="required" class="label label-danger">Required field</p>
<p ng-message="minlength" class="label label-danger">Few letters</p>
<p ng-message="manlength" class="label label-danger">Too much letters</p>
<p ng-message="url" class="label label-danger">Invalid URL</p>
我更改了控制器以在必要时显示验证消息:
case 422: angular.forEach(data, function(value, key){
// I set the field invalid
vm.bookmarkForm[value.property].$setValidity(value.message, false);
});
break;
现在的问题是,在再次提交表单后,先前的验证消息仍保留在屏幕上,并更改此字段的内容以使其变为有效,即使其他字段出错。
每次发送表单数据时如何清除控制器上的这些消息?