利用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);
});
});
}
}
}]);
Demo html代碼(feedback部分請參考 http://www.linuxidc.com/Linux/2015-01/112324.htm ):
<div class="form-group">
<label for="userPassword">密碼</label>
<input type="password" class="form-control" id="userPassword" name="userPassword"
placeholder="請輸入密碼" ng-model="selectedUser.userPassword">
</div>
<div class="form-group has-feedback"
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" class="form-control" id="confirmPassword" name="confirmPassword"
placeholder="請再次輸入密碼" ng-model="selectedUser.confirmPassword" pw-check="userPassword">
<div ng-show="!usrMgrForm.confirmPassword.$pristine && tagName.confirmPassword.$valid">
<span class="glyphicon glyphicon-ok form-control-feedback"></span>
</div>
<div ng-show="!usrMgrForm.confirmPassword.$pristine && usrMgrForm.confirmPassword.$invalid">
<span class="glyphicon glyphicon-remove form-control-feedback"></span>
</div>
</div>
效果如下:
AngularJS權威教程 清晰PDF版 http://www.linuxidc.com/Linux/2015-01/111429.htm
希望你喜歡,並分享我的工作~帶你走近AngularJS系列:
如何在 AngularJS 中對控制器進行單元測試 http://www.linuxidc.com/Linux/2013-12/94166.htm
在 AngularJS 應用中通過 JSON 文件來設置狀態 http://www.linuxidc.com/Linux/2014-07/104083.htm
AngularJS 之 Factory vs Service vs Provider http://www.linuxidc.com/Linux/2014-05/101475.htm
AngularJS —— 使用 ngResource、RESTful APIs 和 Spring MVC 框架提交數據 http://www.linuxidc.com/Linux/2014-07/104402.htm
AngularJS 的詳細介紹:請點這裡
AngularJS 的下載地址:請點這裡