Angularjs 如何在angular中验证由ng repeat填充的元素内的每个字段的值并相应地显示消息?
我有几个值是提取的,需要显示并进行编辑。我已经在每个字段上应用了验证-它工作正常,但我无法显示与之对应的消息 相关的html是Angularjs 如何在angular中验证由ng repeat填充的元素内的每个字段的值并相应地显示消息?,angularjs,validation,angularjs-directive,Angularjs,Validation,Angularjs Directive,我有几个值是提取的,需要显示并进行编辑。我已经在每个字段上应用了验证-它工作正常,但我无法显示与之对应的消息 相关的html是 <body ng-app="app"> <div ng-controller="HistoryController"> {{invalidHistory}} <form name="histories" novalidate ng-cloak> <table border="1px s
<body ng-app="app">
<div ng-controller="HistoryController">
{{invalidHistory}}
<form name="histories" novalidate ng-cloak>
<table border="1px solid black">
<tr>
<td ng-repeat="h in history" ><input ng-model="h" name="history-{{$index}}" ng-class="{error: invalidHistory}" valid-history/> <span>{{histories.history-$index.$error.invalidHistory}}</span></td>
</tr>
</table>
</form>
{{ histories | json}}
</div>
<script type="text/javascript" src="js/angular.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
示例历史记录是一个json文件:包含以下内容:
[“1.6”、“1.8”、“-2.1”、“5.2”、“12.4”、“15.6”、“18.7”、“21.1”]
当重复输入中的任何值不正确时,如何显示消息。为什么{{histories.history-$index.$error.invalidHistory}}
始终为0,即使该值在验证中设置为true或false
谢谢。现在,当任何字段出现以下验证问题时,我都可以获得通用消息<代码>历史记录中的错误在表单中。
var app = angular.module("app", []);
app.service('HistoryService', function($http) {
this.getHistory = function(){
return $http.get('mock/history.json').
success(function(data, status, headers, config) {
return data;
}).
error(function(data, status, headers, config) {
console.log(data);
});
};
});
app.controller('HistoryController', function($scope, HistoryService) {
HistoryService.getHistory().then(function(response){
$scope.history = response.data;
$scope.invalidHistory = "";
});
});
app.directive('validHistory',function() {
var regex = /(^\-3\.0$)|(^\-[0-2]\.[0-9]$)|(^[1-9]?[0-9]\.[0-9]$)/;
var link = function($scope, $element, $attrs, ctrl) {
var validate = function(viewValue) {
console.log(viewValue, typeof viewValue);
var isValid = regex.test(viewValue);
if(!$scope.histories.$dirty){
ctrl.$setValidity('invalidHistory', true);
return viewValue;
} else if(isValid){
ctrl.$setValidity('invalidHistory', true);
return viewValue;
} else{
$scope.invalidHistory = "Invalid Value";
ctrl.$setValidity('invalidHistory', false);
}
};
ctrl.$parsers.unshift(validate);
ctrl.$formatters.push(validate);
$attrs.$observe('invalidHistory', function(viewValue){
// Whenever the comparison model changes we'll re-validate
return validate(viewValue);
});
};
return {
require: 'ngModel',
link: link
};
});