简体   繁体   中英

validate password directive in angularjs

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

angular.module('app')
  .directive('validate', function () {
    return {
      require: "ngModel",   
      link: function postLink(scope, element, attrs, ngModelCtrl) {
        function validate(value){
            var valid = (value === scope.$eval(attrs.validate));
            ngModelCtrl.$setValidtity('equal', valid);
            return valid ? value : undefined;
        }

        ngModelCtrl.$parsers.push(validate);
        ngModelCtrl.$formatters.push(validate);

        $scope.$watch(attrs.validate, function(){
            ngModelCtrl.$setViewValue(ngModelCtrl.$viewvalue);
        })
      }
    };
  });

Can anyone explain me the below questions .

What does the below code do in the directive ?.

$scope.watch(attrs.validate, function(){
    ngModelCtrl.$setViewValue(ngModelCtrl.$viewvalue);
});

How is the value passed to validate() function?.

Check out the documentation of ngModelController . Since this directive requires ngModel, it receives the ngModelController as the fourth argument of the link function. In regards to your other questions:

  1. The $scope.watch (which should really be $scope.$watch ) call sets up a watch on the validate attribute of the element on which the directive is operating. If the validate attribute changes for some reason (eg it's bound to an AngularJS expression whose value changes) then the function passed as the second parameter will be executed. This function resets the view value, which re-triggers the validate function registered as a parser.
  2. Per the ngModelController documentation, the view value is passed to the first parser function, and the result of that function is passed to the next parser, and so forth. Likewise, the model value is passed to the first formatter function and the result is passed to the next formatter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM