<form name="form">
<input type="text" placeholder="請輸入賬號" /> <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>
1 angular.module("Valid",[]) 2 3 .directive("equalTo", function () { 4 return { 5 require: "ngModel", 6 link: function (scope, ele, attrs, ctrl) { 7 8 console.log(scope);//打印當前作用域 9 console.log(attrs);//打印當前標簽屬性列表 10 console.log(ctrl);//打印當前ctrl 11 12 var target = attrs["equalTo"];//獲取自定義指令屬性鍵值 13 14 if (target) {//判斷鍵是否存在 15 scope.$watch(target, function () {//存在啟動監聽其值 16 ctrl.$validate()//每次改變手動調用驗證 17 }) 18 19 // 獲取當前模型控制器的父控制器FormController 20 var targetCtrl = ctrl.$$parentForm[target];//獲取指定模型控制器 21 console.log(targetCtrl) 22 23 ctrl.$validators.equalTo = function (modelValue, viewValue) {//自定義驗證器內容 24 25 var targetValue = targetCtrl.$viewValue;//獲取password的輸入值 26 27 return targetValue == viewValue;//是否等於passwordConfirm的值 28 } 29 30 ctrl.$formatters.push(function (value) { 31 console.log("正在進行數據格式化的值:",value) 32 return value; 33 }) 34 35 ctrl.$parsers.push(function (value) { 36 console.log("正在進行數據轉換的值:",value) 37 return value; 38 }) 39 } 40 } 41 } 42 })
