When using regular input, such as
ngModel)Use the ngModel controller and the object form of the require property in the DDO:
angular.module('myModule', [])
.directive('myDirective', function() {
return {
restrict: 'E',
require: { ngModelCtrl: 'ngModel' },
scope: {
ngModel: '<'
},
bindToController: true,
controllerAs: '$ctrl',
template:
`
`,
controller: function ctrl() {}
};
});
Usage:
By instantiating and using the ng-model controller, the directive will automatically set the form controls as necessary.
angular.module('myModule', [])
.directive('myDirective', function() {
return {
restrict: 'E',
require: { ngModelCtrl: 'ngModel' },
scope: {
ngModel: '<'
},
bindToController: true,
controllerAs: '$ctrl',
template:
`
`,
controller: function ctrl() {}
};
});
ngModel DEMO
myForm.$dirty = {{myForm.$dirty}}
myForm.$pristine = {{myForm.$pristine}}
I recommend isolate scope with ngModel as an input. Output should be done with the $setViewValue method.
For more information, see
AngularJS Developer Guide - Implementing custom form controls (using ngModel)
AngularJS Developer Guide - Component-based application architecture