BetaRide BetaRide - 5 months ago 49x
AngularJS Question

How to add custom validation to an angular component?

I have this angular component where I like to add a custom input validator (see plunker).

I'm trying to access the

in the
function. But it seams that the form is not populated at this time. Later on in the
function it's no problem to access the the input model controller. How can I access the
and add a custom validator?


(function(angular) {
'use strict';

function EmailInputController($log) {
var ctrl = this;

ctrl.$onInit = function() {
// ctrl.myForm.myEmailInput is not populated
//$log.debug("Email view value is: "+(ctrl.myForm.myEmailInput.$viewValue));

ctrl.sendEmail = function() {
$log.debug("Email view value is: " + (ctrl.myForm.myEmailInput.$viewValue));


angular.module('emailInputApp').component('emailInput', {
templateUrl: 'emailInput.html',
controller: EmailInputController,


<form name="$ctrl.myForm">
<input name="myEmailInput" type="email" ng-model="$" required maxlength="15">
<button type="button" ng-click="$ctrl.sendEmail()">Send Email</button>
<p>Your Email addres is {{$}}</p>
<div ng-messages="$ctrl.myForm.myEmailInput.$error" role="alert">
<div ng-message="required">Please enter an email address.</div>
<div ng-message="email">This field must be a valid email address.</div>
<div ng-message="maxlength">This field can be at most 15 characters long.</div>
{{$ctrl.myForm.myEmailInput | json}}


You can add watcher and remove it when not needed anymore.

var removeWatch = $scope.$watch('$ctrl.myForm', function () {
        $log.debug("Email view value is: " + (ctrl.myForm.myEmailInput.$modelValue));