AngularJS - how to change the value of ngModel in custom directive?

Sady picture Sady · Mar 25, 2014 · Viewed 72.5k times · Source

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?

Answer

Carlos Morales picture Carlos Morales · Aug 5, 2015

There are different ways of doing it:

  1. $setViewValue() updates the view and the model. Most cases it is enough.
  2. 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
  3. 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: