Chapter 8
This custom model validator directive must integrate with ngModelController to
provide a consistent validation experience for the user.
We can expose the ngModelController on the scope by providing a name for the
form and a name for the input element. This allows us to access model validity in
the controller. Our validation directive will set the confirmPassword input to valid
if its model value is the same as the user.password model.
Requiring a directive controller
Validation directives require access to the ngModelController, which is the
directive controller for the ng-model directive. We specify this in our directive
definition using the require field. This field takes a string or an array of strings.
Each string must be the canonical name of the directive whose controller we require.
When the required directive is found, its directive controller is injected into the
linking function as the fourth parameter. For example:
require: 'ngModel',
link: function(scope, element, attrs, ngModelController) { ... }
If more than one controller is required, then the fourth parameter will be an array
containing these controllers in the same order as they were required.
If the current element does not contain the specified directive, then
the compiler will throw an error. This can be a good way to ensure
that the other directive has been provided.
Making the controller optional
You can make the require field of the controller optional by putting a '?' in front
of the directive name, for example, require: '?ngModel'. If the directive has not
been provided, then the fourth parameter will be null. If you require more than one
controller then the relevant element in the array of controllers will be null.