我想在我的表单中单击保存按钮(提交)后验证我的输入必填字段并仅显示错误消息。 在angularjs中最好的方法是什么?
谢谢,
答案 0 :(得分:0)
请查看此answer
示例说明您可以在该链接中找到
module = angular.module('app', []);
module.directive('showErrors', function() {
return {
restrict: 'A',
require: '^form',
link: function (scope, el, attrs, formCtrl) {
// find the text box element, which has the 'name' attribute
var inputEl = el[0].querySelector("[name]");
// convert the native text box element to an angular element
var inputNgEl = angular.element(inputEl);
// get the name on the text box
var inputName = inputNgEl.attr('name');
// only apply the has-error class after the user leaves the text box
inputNgEl.bind('blur', function() {
el.toggleClass('has-error', formCtrl[inputName].$invalid);
})
}
}
});
module.controller('NewUserController', function($scope) {
$scope.save = function() {
if ($scope.userForm.$valid) {
alert('User saved');
$scope.reset();
} else {
alert("There are invalid fields");
}
};
$scope.reset = function() {
$scope.user = { name: '', email: '' };
}
});