textarea的默认值采用NG-模型后失踪 [英] Default values of textarea missing after using ng-model

查看:142
本文介绍了textarea的默认值采用NG-模型后失踪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个角度的应用程序中,我使用的是文本框,如下所示:

 < D​​IV CLASS =面板正文中心>
        < textarea的ID =MYTEXT级=表格控行=4>约翰,2
    简,3
    约翰,4
    简,5
        < / textarea的>
    < / DIV>

下面的值约翰,2 ...等被默认加载。然而,当我引入一个NG-模型来访问这些数据,如下所示,默认值显示不出来了。可能是什么回事?

 < textarea的ID =MYTEXTNG模型=mytextvalue级=表格控行=4>


解决方案

文档


  

ngModel 将尝试绑定到通过在当前范围评估前pression给出的属性。如果该属性不已在此范围存在,它将被隐式地创建并添加到范围


所以,这里发生了什么具有以下code:

 < textarea的NG-模式=mytextvalue> ...< / texarea>

在该 NG-模型指令被处理时,它会寻找一个属性 mytextvalue $范围。如果它没有找到一个,它会创建一个空的值,然后进行了空值分配给你的元素。

如果您想为默认值,你就必须explicicly指定 mytextvalue

您可以做,在 HTML NG-INIT

NG-的init =mytextvalue ='约翰,2 \\ nJane,3 \\ nJohn,4 \\ nJane,5'

或者,你可以用它做的的JavaScript 您的控制器上:

$ scope.mytextvalue ='约翰,2 \\ nJane,3 \\ nJohn,4 \\ nJane,5';

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

解决方案

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

这篇关于textarea的默认值采用NG-模型后失踪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆