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?
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.
The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With