Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 856
Sady Avatar asked Mar 25 '14 15:03

Sady


People also ask

How do I update my ngModel value?

If we use two way binding syntax for ngModel the value will be updated. So the default (ngModelChange) function will update the value of ngModel property. i.e., user.Name . And the second (ngModelChange) will be triggered printing the user name value in the console.

What does the [( ngModel )] directive do in angular?

The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.

How does ngModel work?

NgModel works using these two bindings together. First, it passes the data from the component class and set data in FormControl. Second, it passes the data from UI after a specific action is triggered and then changes the value of the control.


1 Answers

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:

  • 1st option is discussed here
  • NgModelController official docs
like image 135
Carlos Morales Avatar answered Oct 10 '22 20:10

Carlos Morales