【问题标题】:How to add ng-model to an at runtime created html object如何将 ng-model 添加到运行时创建的 html 对象
【发布时间】:2015-07-31 08:07:37
【问题描述】:

我有一个像这样的简单 html 表单

<div ng-app="app">
    <form action="" ng-controller="testController" id="parent">
    </form>
</div>

现在我想从 javascript 添加一个输入字段

var app = angular.module('app',[]);
app.controller('testController',testController);
function testController($scope){
    var input = document.createElement('input');
    var form = document.getElementById('parent');

    input.setAttribute("type","number");
    input.setAttribute("id","testId");
    input.setAttribute("name", "test");
    input.setAttribute("ng-model","test");  
    form.appendChild(input);
}

输入字段也按预期生成

<input type="number" id="testId" name="test" ng-model="test">

但此输入字段和$scope.test 之间的 ng-model 不起作用。

【问题讨论】:

  • 在控制器中进行dom操作是错误的做法...您需要使用$compile服务编译新元素
  • 使用指令进行 DOM 操作和编译

标签: javascript angularjs angular-ngmodel


【解决方案1】:

重要提示:你不应该在控制器中进行 dom 操作,你需要使用指令来做到这一点。

也就是说,即使在指令中,如果您要创建动态元素,您也需要对其进行编译以应用角度行为。

var app = angular.module('app', [], function() {})

app.controller('testController', ['$scope', '$compile', testController]);

function testController($scope, $compile) {
  var input = document.createElement('input');
  var form = document.getElementById('parent');

  input.setAttribute("type", "number");
  input.setAttribute("id", "testId");
  input.setAttribute("name", "test");
  input.setAttribute("ng-model", "test");
  $compile(input)($scope)
  form.appendChild(input);
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <form action="" ng-controller="testController" id="parent">
    <div>test: {{test}}</div>
  </form>
</div>

【讨论】:

  • ngModel 不是指令吗?还是我对指令的理解有误?
  • 您可以创建自己的指令,无论何时需要操作 DOM、使用指令或让您拥有
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-09
  • 2014-08-24
  • 2016-12-20
  • 2013-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多