正如 dnc253 所说,您的ng-switch
逻辑有点不对劲。以下将为您提供所需的确切功能。
http://jsfiddle.net/ud3323/AbmsG/4/
HTML
<form ng-app="someApp" name="form" ng-controller="MainCtrl">
<input validate name="LastName" ng-model="form.lastName" dallas len = "5" required />
<div class="errorDiv" ng-switch on="currentError">
<div ng-switch-when="required" style="color: white; background-color: red">required</div>
<div ng-switch-when="len" style="color: white; background-color: red">len</div>
<div ng-switch-when="dallas" style="color: white; background-color: red">dallas</div>
</div>
</form>
JS
angular.module('someApp', [])
.directive('validate', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, ctrl) {
element.bind("keydown keypress", function(event) {
if (event.which === 13) {
scope.$apply(function() {
scope.$eval(attrs.onEnter);
});
event.preventDefault();
}
});
ctrl.$parsers.push(function(val){
if (!val) val = '';
ctrl.$setValidity('required',
val != '');
ctrl.$setValidity('len',
val.length == 5);
ctrl.$setValidity('dallas',
val=='dallas');
return val;
});
}
}
}).controller('MainCtrl', ['$scope', function ($scope) {
$scope.$watch('form.$error', function (errObj) {
if (errObj.required) $scope.currentError = "required";
else if (errObj.len) $scope.currentError = "len";
else if (errObj.dallas) $scope.currentError = "dallas";
}, true);
}]);