ctrl。$ parsers.unshift抛出undefined

时间:2016-03-20 09:37:02

标签: angularjs angularjs-directive

我正在建立一个匹配两个输入字段的自定义指令。 因此,使用ctrl.$parsers.unshift会向我发出错误Cannot read property 'unshift' of undefined。无法弄清楚出了什么问题。 顺便说一下,我正在使用Angular Material Input Fields。

<md-input-container>
  <label>E-Mail</label>
  <input required type="email" name="clientEmail" ng-model="user.clientEmail"
         minlength="10" maxlength="100" ng-pattern="/^.+@.+\..+$/" />
  <div ng-messages="registerForm.clientEmail.$error" role="alert">
    <div ng-message-exp="['required', 'minlength', 'maxlength', 'pattern']">
      Your email must be between 10 and 100 characters long and look like an e-mail address.
    </div>
  </div>
</md-input-container>

<md-input-container>
  <label>E-Mail wiederholen</label>
  <input required type="email" name="clientEmailconfirm" ng-model="user.clientEmailconfirm"
  minlength="10" maxlength="100" ng-pattern="/^.+@.+\..+$/" field-match="{{user.clientEmail}}" />
  <div ng-messages="registerForm.clientEmailconfirm.$error" role="alert">
    <div ng-message-exp="['required', 'minlength', 'maxlength', 'pattern']">
      Your email must be between 10 and 100 characters long and look like an e-mail address.
    </div>
    <div ng-message="fieldMatch">E-Mail do not Match...</div>
  </div>
</md-input-container>

指令:

angular.module('fieldmatcher', []);
app.directive('fieldMatch', ['$rootScope', '$compile', '$parse', function($rootScope, $compile, $parse) {
  return {
    require: ['ngModel'],
    restrict: 'A',
    scope: true,
    link: function(scope, element, attr, ctrl) {
      ctrl.$parsers.unshift(validate);
      ctrl.$formatters.push(validate);

      var validate = function(viewValue) {
        var comparisonModel = attr.fieldMatch;

        if (!viewValue || !comparisonModel) {
          ctrl.$setValidity('fieldMatch', true);
        }

        ctrl.$setValidity('fieldMatch', (viewValue === comparisonModel));
        return viewValue;
      };

      attr.$observe('fieldMatch', function(comparisonModel) {
        return validate(ctrl.$viewValue);
      });
    }
  }
}]);

1 个答案:

答案 0 :(得分:5)

在您的示例中,链接函数的参数ctrl是具有单个控制器元素的数组。

这是因为您使用了require属性的数组值。

请参阅docs ctrl参数:

  

确切的值取决于指令的require属性:
   1.无需控制器:指令自己的控制器,如果没有控制器,则不定义    2.字符串:控制器实例
   3. array:控制器实例数组

只需更改为require: 'ngModel',

在将变量放入解析器和格式化程序数组之前定义var validate = function(...