Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default values of textarea missing after using ng-model

i have an angular app in which i am using a textbox as follows:

    <div class="panel-body text-center">
        <textarea id="mytext" class="form-control" rows="4">John,2
    Jane,3
    John,4
    Jane,5
        </textarea>
    </div>

Here the values John,2...etc are loaded by default. However when i introduce an ng-model to access this data as follows, the default values do not show up anymore. What might be happening?

<textarea id="mytext" ng-model="mytextvalue" class="form-control" rows="4">
like image 322
Abhishek Avatar asked Aug 19 '14 18:08

Abhishek


People also ask

Can we use ngModel in textarea?

<input> and <textarea> attributesAll of the attributes that can be used with normal <input> and <textarea> elements can be used on elements inside <mat-form-field> as well. This includes Angular directives such as ngModel and formControl .

Can textarea have value?

<textarea> does not support the value attribute.

What is the use of NG model?

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 textarea in angular?

They provide data-binding, which means they are part of the AngularJS model, and can be referred to, and updated, both in AngularJS functions and in the DOM. They provide validation. Example: an <textarea> element with a required attribute, has the $valid state set to false as long as it is empty.


1 Answers

From the docs:

ngModel will try to bind to the property given by evaluating the expression on the current scope. If the property doesn't already exist on this scope, it will be created implicitly and added to the scope.

So what's happening here with the following code:

<textarea ng-model="mytextvalue" >...</texarea>

When the ng-model directive is processed, it will look for a property mytextvalue on $scope. When it doesn't find one, it will create an empty value and then proceed to assign that empty value to your element.

If you want to default the value, you'll have to explicicly specify a value for mytextvalue

You can do that in HTML with ng-init

ng-init="mytextvalue='John,2\nJane,3\nJohn,4\nJane,5'"

Or you can do it with JavaScript on your controller:

$scope.mytextvalue = 'John,2\nJane,3\nJohn,4\nJane,5';
like image 86
KyleMit Avatar answered Sep 26 '22 22:09

KyleMit