控制器ngModel在我的自定义指令中解开

时间:2017-09-21 07:27:32

标签: javascript jquery angularjs

我在我的角度应用程序中添加了一个自定义指令,如果邮件有效则负责调整,该指令似乎工作得非常好,因为我收到了错误消息:

myApp.directive('validateEmail', function(ValidationService) {
    return {
      require: 'ngModel',
      controller: function($element) {
        var ctrl = $element.controller('ngModel');

        ctrl.$validators.validateEmail =
          function(modelValue, viewValue) {
            return ValidationService.isValidEmail(viewValue);
        };
      }
    };
});

当我尝试提交表单时,我在控制台中遇到了以下奇怪的错误:

  

错误:ctrl未定义   控制器@ http://localhost:8080/MYAPP/js/app.js:293:9   调用@ https://code.angularjs.org/1.5.1/angular.js:4625:16   $ ControllerProvider /这$ gethttps://code.angularjs.org/1.5.1/angular.js:9886:24   nodeLinkFn @ https://code.angularjs.org/1.5.1/angular.js:8870:34   compositeLinkFn @ https://code.angularjs.org/1.5.1/angular.js:8248:13   publicLinkFn @ https://code.angularjs.org/1.5.1/angular.js:8128:30   compilationGenerator /< @ https://code.angularjs.org/1.5.1/angular.js:8467:16   boundTranscludeFn @ https://code.angularjs.org/1.5.1/angular.js:8266:16   controllersBoundTransclude @ https://code.angularjs.org/1.5.1/angular.js:8963:20   ngIfWatchAction @ https://code.angularjs.org/1.5.1/angular.js:25178:15   $消化@ https://code.angularjs.org/1.5.1/angular.js:16728:23   $适用@ https://code.angularjs.org/1.5.1/angular.js:16992:13   ngModelPostLink /< @ https://code.angularjs.org/1.5.1/angular.js:26838:15   调度@ http://localhost:8080/MYAPP/js/jquery-3.1.1.min.js:3:10263   添加/ q.handle @ http://localhost:8080/MYAPP/js/jquery-3.1.1.min.js:3

8325

1 个答案:

答案 0 :(得分:2)

将控制器更改为链接。

myApp.directive('validateEmail', function(ValidationService) {
    return {
      require: 'ngModel',
      link: function (scope, element, attrs, ctrl) {
        ctrl.$validators.validateEmail =
          function(modelValue, viewValue) {
            return ValidationService.isValidEmail(viewValue);
        };
      }
    };
});