I am using AngularJS and I created a directive that requires 'ngModel':
'use strict';
angular.module('spot.im.embed').directive('sayBox', ['$sce', '$timeout', '$parse',
function($sce, $timeout, $parse) {
return {
restrict: 'EA',
require: 'ngModel',
scope: {
},
link: function(scope, iElement, iAttrs, ngModel) {
ngModel.$viewValue = 'adasd';
}
}
}
]);
For reasons I don't know, the ng-model changes doesn't impact the view. Why is that? Is this the right way to change the ngModel value from a directive?
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 ngModel directive binds an input , select , textarea (or custom form control) to a property on the scope using NgModelController, which is created and exposed by this directive. ngModel is responsible for: Binding the view into the model, which other directives such as input , textarea or select require.
The ngModel directive is a directive that is used to bind the values of the HTML controls (input, select, and textarea) or any custom form controls, and stores the required user value in a variable and we can use that variable whenever we require that value. It also is used during form validations.
Also ngValue is a one-way binding, and ngModel is a two-way binding.
$viewValue is property, $setViewValue is method that you are probably looking for
link: function (scope, iElement, iAttrs, ngModel) {
ngModel.$setViewValue('adasd');
ngModel.$render(); // depends – if you want update input value or only model value in the scope
}
$setViewValue(value, trigger);
This method should be called when an input directive want to change the view value; typically, this is done from within a DOM event handler.
documentation: https://docs.angularjs.org/api/ng/type/ngModel.NgModelController
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