【发布时间】:2015-06-24 04:35:13
【问题描述】:
谁能解释一下这个密码匹配是如何工作的?我浏览了文档,但对 require:ngModel 控制器感到困惑。
在脚本里面,这三行是什么意思:
- var originalModel = $parse(attrs.valueMatches),
- secondModel = $parse(attrs.ngModel);
- ngModel.$setValidity(attrs.name, newValue === secondModel(scope));
这里的attrs.ngModel 是指ngModel 控制器还是指令?
attrs.ngModel是获取第一个输入字段的属性还是确认密码输入字段?
attrs.name - 我在代码中没有看到任何 name 属性。
<!DOCTYPE html>
<html ng-app="myApp" >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script>
"use strict";
var app = angular.module('myApp', [])
app.directive('valueMatches', ['$parse', function ($parse) {
return {
require: 'ngModel',
link: function (scope, elm, attrs, ngModel) {
var originalModel = $parse(attrs.valueMatches),
secondModel = $parse(attrs.ngModel);
// Watch for changes to this input
scope.$watch(attrs.ngModel, function (newValue) {
ngModel.$setValidity(attrs.name, newValue === originalModel(scope));
});
// Watch for changes to the value-matches model's value
scope.$watch(attrs.valueMatches, function (newValue) {
ngModel.$setValidity(attrs.name, newValue === secondModel(scope));
});
}
};
}]);
</script>
<title>Registration Form</title>
</head>
<body>
<div class="container">
<h2 class="text-muted">Registration form</h2>
<div>
<form name="myForm" action="RegistrationServlet.do" method="POST" novalidate>
First name:<input type="text" class="form-control input-sm" name="uname" ng-pattern="/^[a-zA-Z]{3,20}/" ng-model="uname" placeholder="First Name" required/>
Password:<input type="password" class="form-control input-sm glyphicon glyphicon-ok" name="pwd" ng-model="pwd" required />
Confirm Password: <input type="password" class="form-control input-sm glyphicon glyphicon-ok" name="pwd2" ng-model="pwd2" value-matches="pwd" required/>
<span class="help-block" style="color:red" ng-show="myForm.pwd2.$dirty && myForm.pwd2.$invalid">Passwords did not match<br></span><br>
</form>
</div>
</div>
</body>
</html>
【问题讨论】:
标签: angularjs