问题
Can anyone explain me on how this piece of code works.
HTML Markup
<input type="password" ng-model="password" class="form-control" placeholder="Password" required>
<input type="password" ng-model="confirm_password" class="form-control" placeholder="Password" required validate-equals="password">
Directive Code
'use strict';
angular.module('raJwtApp')
.directive('validateEquals', function () {
return {
require: "ngModel",
link: function postLink(scope, element, attrs, ngModelCtrl) {
function validate(value){
console.log(value, scope.$eval(attrs.validateEquals));
var valid = (value === scope.$eval(attrs.validateEquals));
ngModelCtrl.$setValidity('equal', valid);
return valid ? value : undefined;
}
ngModelCtrl.$parsers.push(validate);
ngModelCtrl.$formatters.push(validate);
scope.$watch(attrs.validateEquals, function(){
ngModelCtrl.$setViewValue(ngModelCtrl.$viewValue);
})
}
};
});
Can anyone explain me the below questions
.
What does the below code do in the directive
?. I don't really understand on how this password match directive works?.
$scope.watch(attrs.validateEquals, function(){
//ngModelCtrl.$viewValue always returns undefined
ngModelCtrl.$setViewValue(ngModelCtrl.$viewValue);
});
回答1:
Angular doesn't have a $setDirty (although it does have a $setPristine), so the way to set a model as dirty is via its control:
ngModelCtrl.$setViewValue(ngModelCtrl.$viewValue);
In your directive, therefore, the $watch is checking for a change to the validateEquals attribute (password), and then sets the model to dirty.
回答2:
<form name="password_form">
<input type="password" ng-model="password" class="form-control" placeholder="Password" required>
<input type="password" ng-model="confirm_password" class="form-control" placeholder="Password" required validate-equals="password">
</form>
<button ng-disabled="password_form.$invalid">save</button>
in <form>
, you can do angular validation by checking a form's flags such as $invalid
or $error
(https://docs.angularjs.org/guide/forms (Custom Validation))
This is useful for simple validation such as:
- a required field (adding
required
to<input>
) or - a minimum # of characters (adding
min='5'
)
and password_form.$invalid
will automatically be set if either requirements fail.
The validate-equals
is a directive to set the form's $invalid
(or $dirty
?) flag manually if the two password fields don't match.
$setViewValue
is called to re-evaluated the form's validity.
The validation functions are executed every time an input is changed ($setViewValue is called) or whenever the bound model changes.
来源:https://stackoverflow.com/questions/28035944/can-anyone-explain-me-this-password-match-directive