0
我有2個字段。我試圖驗證field 2與field1不一樣。我使用了一個指令跨輸入的角度自定義表單驗證
它的工作原理,但我的問題是圍繞增強一點。只有在字段2中輸入數據時才起作用。在字段1中更改數據時它不起作用。換句話說,如果字段1是「Babbalas」並且您在字段2中鍵入「Babbalas」,它會正確顯示我的驗證消息。如果您更改了字段2,則會正確進行驗證(因爲現在字段不一樣)。但是,如果你去改變域1,它不會改變域2上的驗證信息,是否有辦法實現這一點。
我有我做了什麼
http://plnkr.co/edit/OcwyoXwjcbVmTYuKN5hT?p=preview
這裏Plunker是我的index.html
<!DOCTYPE html>
<html ng-app="angularjs-starter">
<head lang="en">
<meta charset="utf-8">
<title>Custom Plunker</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
<link rel="stylesheet" href="style.css">
<script>
document.write('<base href="' + document.location + '" />');
</script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<form name="myForm" ng-submit="doSomething()">
<div>
<input type="text" name="item1" ng-model="data.item1" required/>
<span class="invalid" ng-show="myForm.item1.$error.required">required</span>
<br/>
</div>
<div>
<input type="text" name="item2" ng-model="data.item2" validate-item2 required/>
<span class="invalid" ng-show="myForm.item2.$error.validateItem2">
Cannot be the same as item1</span>
<span class="invalid" ng-show="myForm.item2.$error.required">required</span>
<br/>
</div>
<button type="submit" ng-disabled="myForm.$invalid">Submit</button>
</form>
</body>
</html>
和我的JS文件
var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope) {
$scope.doSomething = function() {
alert('Submitted!');
}
});
app.directive('validateItem2', function(){
return {
require: 'ngModel',
link: function(scope, elem, attr, ngModel) {
ngModel.$parsers.unshift(function(value) {
var valid = value != scope.data.item1;
ngModel.$setValidity('validateItem2', valid);
return valid ? value : undefined;
});
}
};
});