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?
There are different ways of doing it:
$setViewValue()
updates the view and the model. Most cases it is enough.$viewValue
and $modelValue
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: