0

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?.

1 Answer 1

1

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 (e.g. 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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.