2017-09-21 56 views
0

我自定義指令添加到我的角度應用程序,它負責向verfy如果郵件是有效還是無效,該指令似乎工作得很好,因爲我得到了錯誤的信息:控制器ngModel undifined在我的自定義指令

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

當我試圖提交我的形式我在控制檯得到如下奇怪的錯誤:

Error: ctrl is undefined [email protected]http://localhost:8080/MYAPP/js/app.js:293:9 [email protected]https://code.angularjs.org/1.5.1/angular.js:4625:16 $ControllerProvider/this.$gethttps://code.angularjs.org/1.5.1/angular.js:9886:24 [email protected]https://code.angularjs.org/1.5.1/angular.js:8870:34 [email protected]https://code.angularjs.org/1.5.1/angular.js:8248:13 [email protected]https://code.angularjs.org/1.5.1/angular.js:8128:30 compilationGenerator/<@https://code.angularjs.org/1.5.1/angular.js:8467:16 [email protected]https://code.angularjs.org/1.5.1/angular.js:8266:16 [email protected]https://code.angularjs.org/1.5.1/angular.js:8963:20 [email protected]https://code.angularjs.org/1.5.1/angular.js:25178:15 [email protected]https://code.angularjs.org/1.5.1/angular.js:16728:23 [email protected]https://code.angularjs.org/1.5.1/angular.js:16992:13 ngModelPostLink/<@https://code.angularjs.org/1.5.1/angular.js:26838:15 [email protected]http://localhost:8080/MYAPP/js/jquery-3.1.1.min.js:3:10263 add/[email protected]http://localhost:8080/MYAPP/js/jquery-3.1.1.min.js:3 :

回答

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

THX你救了我的一天:) – selma

相關問題