2015-08-30 46 views
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; 
      }); 
     } 
    }; 
}); 

回答

0

你将不得不通过item1作为指令的范围参数,并在那里观察其值。在watch方法中,您可以验证id这两个项目是否具有相同的值。