htmlhtml
<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>
jsgit
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; }) } } } })
model:https://tianyouh.github.io/angularPasswordConfirm/github