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

Abh*_*hek 6 twitter-bootstrap angularjs

我有一个角度应用程序,我在其中使用如下文本框:

    <div class="panel-body text-center">
        <textarea id="mytext" class="form-control" rows="4">John,2
    Jane,3
    John,4
    Jane,5
        </textarea>
    </div>
Run Code Online (Sandbox Code Playgroud)

这里默认加载值John,2 ...等.但是,当我按如下方式引入ng-model访问此数据时,默认值不再显示.可能会发生什么?

<textarea id="mytext" ng-model="mytextvalue" class="form-control" rows="4">
Run Code Online (Sandbox Code Playgroud)

Kyl*_*Mit 12

来自文档:

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

那么这里发生的事情如下:

<textarea ng-model="mytextvalue" >...</texarea>
Run Code Online (Sandbox Code Playgroud)

ng-model被处理的指令,它会寻找一个属性mytextvalue$scope.如果找不到,则会创建一个空值,然后继续将该空值分配给您的元素.

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

你可以在HTMLng-init

ng-init="mytextvalue='John,2\nJane,3\nJohn,4\nJane,5'"
Run Code Online (Sandbox Code Playgroud)

或者您可以在控制器上使用JavaScript执行此操作:

$scope.mytextvalue = 'John,2\nJane,3\nJohn,4\nJane,5';
Run Code Online (Sandbox Code Playgroud)