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/