Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the ngModel value from a directive [duplicate]

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?

like image 462
Naor Avatar asked Aug 10 '14 09:08

Naor


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.

Is ngModel attribute directive?

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.

What is [( ngModel )] used for?

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.

What is the difference between ngValue and ngModel?

Also ngValue is a one-way binding, and ngModel is a two-way binding.


1 Answers

$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

like image 191
Krzysztof Safjanowski Avatar answered Oct 28 '22 18:10

Krzysztof Safjanowski