$ attrs undefined angular directive用于比较密码和密码重复

时间:2017-02-20 16:42:42

标签: angularjs mean-stack

我正在学习平均堆栈开发并遵循视频教程课程。一切都很顺利,直到我尝试匹配两个密码字段时遇到此错误。 "密码"和"确认密码" 我正在编写确切的代码作为教程但我在命令行中遇到以下错误(Gulp serve)

  

错误" $ attrs"是不是没有定义

     

错误" $ attrs"是不是没有定义

这是代码

export function CompareToDirective($parse) {
'ngInject'
return {
    require: 'ngModel',
    link: function (scope, elm, attrs, ngModel) {
        var mainModel = $parse(attrs.compareTo);
        var secondModel = $parse(attrs.ngModel);

        scope.$watch(attrs.ngModel, function (newValue) {
            ngModel.$setValidity($attrs.name, newValue === mainModel(scope));
        });

        scope.$watch(attrs.compareTo, function (newValue) {
            ngModel.$setValidity($attrs.name, newValue === secondModel(scope));
        });
    }
}

}

修改

这里是I'试图验证以防万一

<form name="register">
                <div class="form-group">
                    <label>Email address</label>
                    <input type="email" class="form-control">
                </div>
                <div class="form-group">
                    <label>Password</label>
                    <input type="password" class="form-control" name="pwd" ng-model="pwd">
                </div>
                <div class="form-group">
                    <label>Password Confirm</label>
                    <input type="password" class="form-control" compareTo="pwd" name="pwdConfirm" ng-model="pwdConfirm">
                </div>
                <span ng-show="register.pwdConfirm.$invalid">Passwords do not match</span>
                <button type="submit" class="btn btn-default">Submit</button>
            </form>

1 个答案:

答案 0 :(得分:0)

确定。我能够让它运作起来。请在下面找到代码

.directive("compareto", function($parse) {
  return {
  require: 'ngModel',
  link: function (scope, elm, attrs, ngModel) {
    var mainModel = $parse(attrs.compareto);
    var secondModel = $parse(attrs.ngModel);

    scope.$watch(attrs.ngModel, function (newValue) {
          ngModel.$setValidity(attrs.name, newValue === mainModel(scope));
    });

    scope.$watch(attrs.compareto, function (newValue) {
        ngModel.$setValidity(attrs.name, newValue === secondModel(scope));
    });
}
}
});

和表格将是

<form name="register">
            <div class="form-group">
                <label>Email address</label>
                <input type="email" class="form-control">
            </div>
            <div class="form-group">
                <label>Password</label>
                <input type="password" class="form-control" name="pwd" ng-model="pwd">
            </div>
            <div class="form-group">
                <label>Password Confirm</label>
                <input type="password" class="form-control" compareto="pwd" name="pwdConfirm" ng-model="pwdConfirm">
            </div>
            <span ng-show="register.pwdConfirm.$invalid">Passwords do not match</span>
            <button type="submit" class="btn btn-default">Submit</button>
        </form>