在angularjs中验证密码指令 [英] validate password directive in angularjs

查看:88
本文介绍了在angularjs中验证密码指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以向我解释这段代码是如何工作的。

Can anyone explain me on how this piece of code works.

HTML标记

<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">

指令代码

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);
});

如何传递给 validate() function?。

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

推荐答案

查看 ngModelController 。由于该指令需要ngModel,因此它接收ngModelController作为链接函数的第四个参数。关于您的其他问题:

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. $ scope.watch (应该是真的是 $ scope。$ watch )调用设置监视指令运行的元素的validate属性。如果validate属性由于某种原因而改变(例如,它绑定到值改变的AngularJS表达式),则将执行作为第二个参数传递的函数。此函数重置视图值,重新触发注册为解析器的validate函数。

  2. 根据ngModelController文档,视图值传递给第一个解析器函数,结果为该函数被传递给下一个解析器,依此类推。同样,模型值传递给第一个格式化程序函数,结果传递给下一个格式化程序。

  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.

这篇关于在angularjs中验证密码指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆