【问题标题】:Default values of textarea missing after using ng-model使用 ng-model 后缺少 textarea 的默认值
【发布时间】:2014-10-12 23:10:53
【问题描述】:

我有一个 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>

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

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

【问题讨论】:

标签: angularjs twitter-bootstrap


【解决方案1】:

来自docs

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

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

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

处理ng-model 指令时,它将在$scope 上查找属性mytextvalue。如果找不到,它将创建一个空值,然后继续将该空值分配给您的元素。

如果您想默认该值,您必须明确指定 mytextvalue 的值

您可以在 HTML 中使用ng-init

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

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

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

【讨论】:

    【解决方案2】:

    一种更简洁的方法(仅使用角度):

    在您的控制器上:

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

    在你看来:

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

    希望有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-04
      • 1970-01-01
      • 2012-11-26
      • 2015-11-23
      • 1970-01-01
      • 1970-01-01
      • 2017-08-29
      相关资源
      最近更新 更多