There are different ways of doing it:
$setViewValue()updates the view and the model. Most cases it is enough.- If you want to disconnect view from the model (e.g. model is a number but view is a string with thousands separators) then you could access directly to
$viewValueand$modelValue - If you also want to overwrite the content of
ng-model(e.g. the directive changes the number of decimals, updating also the model), injectngModel: '='on the scope and setscope.ngModel
e.g.
return {
restrict: 'A',
require: 'ngModel',
scope: {
ngModel: '='
},
link: function (scope, element, attrs, ngModelCtrl) {
function updateView(value) {
ngModelCtrl.$viewValue = value;
ngModelCtrl.$render();
}
function updateModel(value) {
ngModelCtrl.$modelValue = value;
scope.ngModel = value; // overwrites ngModel value
}
...
LINKS:
- 1st option is discussed here
- NgModelController official docs