我有以下代码/ plunkr,由于某种原因,form.name。$ invalid始终为true(请参阅输入框后面的span)。 Angular的文档没有说明如何设置$ invalid值。我有一个预感,它在我有ctrl.$error.taken = true/false
的javascript中有一些关系,只是在$ error对象集上有一个对象,$ invalid为true。知道角度如何在幕后工作的人可以帮助我吗?
如果名称与正则表达式不匹配,我希望显示“名称必须是字母数字”错误,但如果名称是列表中的名称,我希望显示“名称已被采用”错误。如果字段是这两个错误之一,我还会显示文本“错误”。所有这些都是有效的,除了总是显示“错误”这个词。我试图遵循使用$ invalid的angular标准。
查看:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-forms-async-validation-production</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="form-example1">
<form name="form" class="css-form" novalidate>
<div>
Username:
<input type="text" ng-model="name" name="name" username />
<span ng-show="form.name.$invalid">error</span>
<br />{{name}}<br />
<span ng-show="form.name.$error.badContent">Name must be alpha-numeric</span>
<span ng-show="form.name.$error.taken">Name is already taken!</span>
</div>
</form>
</body>
</html>
脚本:
(function(angular) {
'use strict';
var app = angular.module('form-example1', []);
var NAME_REGEXP = /^([a-zA-Z0-9])*$/;
app.directive('username', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
var names = ['Jim', 'John', 'Jill', 'Jackie'];
ctrl.$validators.username = function(modelValue, viewValue) {
if (ctrl.$isEmpty(modelValue)) {
return true; // consider empty model valid
}
ctrl.$error.taken = names.indexOf(modelValue) > -1;
ctrl.$error.badContent = !NAME_REGEXP.test(modelValue);
return !ctrl.$error.taken && !ctrl.$error.badContent;
};
}
};
});
})(window.angular);
Plunkr: https://plnkr.co/edit/LBRR14PpjAQigafOVTgQ?p=preview
答案 0 :(得分:1)
JS
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.model = {};
});
app.directive('validateAlphaNumeric', function () {
var REGEX = /^([a-zA-Z0-9])*$/;
return {
require: 'ngModel',
link: function (scope, element, attrs, ctrl) {
ctrl.$validators.alphaNumeric = function (modelValue, viewValue) {
if (REGEX.test(viewValue)) {
return true
}
return false;
};
}
};
});
app.directive('validateUserNotTaken', function () {
return {
require: 'ngModel',
link: function (scope, element, attrs, ctrl) {
var names = ['Jim', 'John', 'Jill', 'Jackie'];
ctrl.$validators.userNotTaken = function (modelValue, viewValue) {
if (names.indexOf(modelValue) == -1) {
return true
}
return false;
};
}
};
});
HTML
<body ng-controller="MainCtrl">
<form name="myForm">
<input type="text" validate-alpha-numeric validate-user-not-taken ng-model="model.value1">
<p ng-if="myForm.$error.alphaNumeric">Should be alphanumeric</p>
<p ng-if="myForm.$error.userNotTaken">User Exists!</p>
<p ng-if="myForm.$error.alphaNumeric || myForm.$error.userNotTaken">Error</p>
</form>
</body>