【发布时间】:2014-10-14 19:40:39
【问题描述】:
我想验证我输入的必填字段,并在单击表单中的保存按钮(提交)后仅显示错误消息。 在 angularjs 中最好的方法是什么?
谢谢,
【问题讨论】:
-
你尝试过的\
标签: javascript html angularjs validation
我想验证我输入的必填字段,并在单击表单中的保存按钮(提交)后仅显示错误消息。 在 angularjs 中最好的方法是什么?
谢谢,
【问题讨论】:
标签: javascript html angularjs validation
请查看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: '' };
}
});
【讨论】: