利用AngularJS的directive,我们可以很方便的实现检验功能。代码如下:
// 密码验证directive
ftitAppModule.directive('pwCheck', [function () {
return {
require: 'ngModel',
link: function (scope, elem, attrs, ctrl) {
var firstPassword = '#' + attrs.pwCheck;
elem.add(firstPassword).on('keyup', function () {
scope.$apply(function () {
var v = elem.val()===$(firstPassword).val();
ctrl.$setValidity('pwmatch', v);
});
});
}
}
}]);
<div>
<label for="userPassword">密码</label>
<input type="password"
placeholder="请输入密码" ng-model="selectedUser.userPassword">
</div>
<div
ng-class="{'has-success' : !usrMgrForm.confirmPassword.$pristine && usrMgrForm.confirmPassword.$valid,
'has-error' : !usrMgrForm.confirmPassword.$pristine && usrMgrForm.confirmPassword.$invalid }">
<label for="confirmPassword">确认密码</label>
<input type="password"
placeholder="请再次输入密码" ng-model="selectedUser.confirmPassword" pw-check="userPassword">
<div ng-show="!usrMgrForm.confirmPassword.$pristine && tagName.confirmPassword.$valid">
<span></span>
</div>
<div ng-show="!usrMgrForm.confirmPassword.$pristine && usrMgrForm.confirmPassword.$invalid">
<span></span>
</div>
</div>
效果如下:
希望你喜欢,并分享我的工作~带你走近AngularJS系列:
在 AngularJS 应用中通过 JSON 文件来设置状态
AngularJS 之 Factory vs Service vs Provider