A unique feature of your setup is the custom input control you are using. This specialized input control consists of two textboxes, but it actually operates as a unified entity.
To ensure that your custom input control fully "supports" ngModel
and seamlessly integrates with other directives requiring ngModel
, your directive should also include a require: ngModel
statement and utilize the ngModelController
functionalities for seamless integration.
Simply binding to scope: { ngModel: "=" }
may not be sufficient. While this enables two-way binding to a model associated with the ng-model
attribute, unexpected behavior may occur when attempting to set the value using scope.ngModel = "something"
.
The Angular documentation features an illustrative example of a custom input control within the context of the ngModelController
. In essence, managing the $viewValue
update upon View alterations and syncing the View adjustments with model changes are crucial elements to coordinate.
.directive("sampleDirective", function(){
return {
require: "ngModel",
scope: true,
template: '<input ng-model="d.input1" ng-change="viewChanged()">\
<input ng-model="d.input2" ng-change="viewChanged()">',
link: function(scope, element, attrs, ngModel){
var d = scope.d = {};
ngModel.$render = render;
scope.viewChanged = read;
// rendering based on model modifications
function render(){
var modelValue = ngModel.$modelValue || "";
var length = modelValue.length;
d.input1 = modelValue.slice(0, length/2);
d.input2 = length > 1 ? modelValue.slice(length/2, length) : "";
};
// setting the model based on DOM updates
function read(){
var newViewValue = d.input1 + d.input2;
ngModel.$setViewValue(newViewValue);
}
}
};
});
This approach allows your control to interact effectively with any other directive supporting ngModel
, such as required
, ng-pattern
, or ng-change
, and facilitates participation in form validations:
<div ng-form="form1">
<sample-directive ng-model="foo" maxlength="8" ng-change="doSomething()">
</sample-directive>
</div>
Check out the Demo