Default values of textarea missing after using ng-model

匿名 (未验证) 提交于 2019-12-03 08:44:33

问题:

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"> 

回答1:

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'; 


回答2:

A cleaner way to go about it(using only angular):

On your controllers:

$scope.item = {'mytextvalue' : 'John,2 Jane,3 John,4 Jane,5'}; 

on your view:

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

Hope that helps!



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!