twitter-bootstrap 使用 ng-model 后缺少 textarea 的默认值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25390401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 21:21:09  来源:igfitidea点击:

Default values of textarea missing after using ng-model

angularjstwitter-bootstrap

提问by Abhishek

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

我有一个 angular 应用程序,我在其中使用了一个文本框,如下所示:

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

此处默认加载值 John,2...etc。然而,当我引入一个 ng-model 来访问这个数据时,默认值不再显示。可能会发生什么?

<textarea id="mytext" ng-model="mytextvalue" class="form-control" rows="4">

回答by KyleMit

From the docs:

文档

ngModelwill 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.

ngModel将尝试绑定到通过评估当前作用域上的表达式给出的属性。如果此范围内尚不存在该属性,则会隐式创建该属性并将其添加到范围中。

So what's happening here with the following code:

那么下面的代码发生了什么:

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

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

ng-model被处理的指令,它会寻找一个属性mytextvalue$scope。当它没有找到时,它会创建一个空值,然后继续将该空值分配给您的元素。

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

如果要默认值,则必须明确指定一个值 mytextvalue

You can do that in HTMLwith ng-init

你可以在HTML 中使用ng-init

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

Or you can do it with JavaScripton your controller:

或者你可以在你的控制器上使用JavaScript

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

回答by Eddy Ferreira

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

一种更简洁的方法(仅使用 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!

希望有帮助!