我想在AngularJS中创建一个密码/电子邮件确认指令,但到目前为止,我看到的所有这些指令都依赖于大量的DOM戳或拉入jQuery。如果可以的话,我只想依赖于$scope属性。那么最好的方法是什么呢?
发布于 2013-07-05 01:24:08
在研究了实现这类指令的许多有用的方法之后,我想出了如何在不操纵DOM或使用jQuery的情况下实现它。这是一个Plunk that shows how。
它涉及到使用:
监视输入fields
我希望这对一些人有用。要点如下:
var app = angular.module('app', [], function() {} );
app.directive('match', function($parse) {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ctrl) {
scope.$watch(function() {
return $parse(attrs.match)(scope) === ctrl.$modelValue;
}, function(currentValue) {
ctrl.$setValidity('mismatch', currentValue);
});
}
};
});
app.controller('FormController', function ($scope) {
$scope.fields = {
email: '',
emailConfirm: ''
};
$scope.submit = function() {
alert("Submit!");
};
});
然后,在HTML中:
<!DOCTYPE html>
<html ng-app="app">
<head lang="en">
<meta charset="utf-8">
<title>Custom Plunker</title>
<link rel="stylesheet" href="style.css">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="FormController">
<form name='appForm' ng-submit='submit()'>
<div class="control-group">
<label class="control-label required" for="email">Email</label>
<div class="controls">
<input id="email" name="email" ng-model="fields.email"
class="input-xlarge" required="true" type="text" />
<p class="help-block">user@example.com</p>
</div>
</div>
<div class="control-group">
<label class="control-label required" for="emailConfirm">Confirm Email</label>
<div class="controls">
<input name="emailConfirm" ng-model="fields.emailConfirm"
class="input-xlarge" required="true"
type="text" match="fields.email" />
<div ng-show="appForm.emailConfirm.$error.mismatch">
<span class="msg-error">Email and Confirm Email must match.</span>
</div>
</div>
</div>
<button ng-disabled='appForm.$invalid'>Submit</button>
</form>
</body>
</html>
发布于 2014-08-20 07:32:21
这对我来说很好用:
指令:
angular.module('myApp').directive('matchValidator', [function() {
return {
require: 'ngModel',
link: function(scope, elm, attr, ctrl) {
var pwdWidget = elm.inheritedData('$formController')[attr.matchValidator];
ctrl.$parsers.push(function(value) {
if (value === pwdWidget.$viewValue) {
ctrl.$setValidity('match', true);
return value;
}
if (value && pwdWidget.$viewValue) {
ctrl.$setValidity('match', false);
}
});
pwdWidget.$parsers.push(function(value) {
if (value && ctrl.$viewValue) {
ctrl.$setValidity('match', value === ctrl.$viewValue);
}
return value;
});
}
};
}])
使用
<input type="email" ng-model="value1" name="email" required>
<input type="email" ng-model="value2" name="emailConfirm" match-validator="email" required>
显示错误
<div ng-if="[[yourFormName]].emailConfirm.$error">
<div ng-if="[[yourFormName]].emailConfirm.$error.match">
Email addresses don't match.
</div>
</div>
https://stackoverflow.com/questions/17475595
复制相似问题