AngularJS - how to change the value of ngModel in custom directive?
angularjs, angularjs-directive, angularjs-model, javascript
Solution
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 `$viewValue` and `$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), inject `ngModel: '='` on the scope and set `scope.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
Problem
Lets take a look to my directive: ``` angular.module('main').directive('datepicker', [ function() { return { require: '?ngModel', link: function(scope, element, attributes, ngModel) { ngModel.$modelValue = 'abc'; // this does not work // how do I change the value of the model? ``` So, how do I change the value of the ng-model?