html代碼
<form name="form"> <input type="password" name="password" ng-model="password" required placeholder="請輸入密碼"> <input type="password" name="passwordConfirm" ng-model="passwordConfirm" equal-to="password" placeholder="請再次輸入密碼"> <span ng-show="form.passwordConfirm.$error.equalTo">兩次密碼不一致</span> </form>
js
angular.module("Valid",[]).directive("equalTo", function () { return { require: "ngModel", link: function (scope, ele, attrs, ctrl) { console.log(scope);//列印當前範圍 console.log(attrs);//列印當前標籤屬性列表 console.log(ctrl);//列印當前ctrl var target = attrs["equalTo"];//擷取自訂指令屬性索引值 if (target) {//判斷鍵是否存在 scope.$watch(target, function () {//存在啟動監聽其值 ctrl.$validate()//每次改變手動調用驗證 }) // 擷取當前模型控制器的父控制器FormController var targetCtrl = ctrl.$$parentForm[target];//擷取指定模型控制器 console.log(targetCtrl) ctrl.$validators.equalTo = function (modelValue, viewVale) {//自訂驗證器內容 var targetValue = targetCtrl.$viewValue;//擷取password的輸入值 return targetValue == viewVale;//是否等於passwordConfirm的值 } ctrl.$formatters.push(function (value) { console.log("進行中資料格式化的值:",value) return value; }) ctrl.$parsers.push(function (value) { console.log("進行中資料轉換的值:",value) return value; }) } } }})
示範地址:https://tianyouh.github.io/angularPasswordConfirm/