如何将 ng-model 添加到运行时创建的 html 对象

How to add ng-model to an at runtime created html object

我有一个像这样的简单 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 操作,你需要使用指令来做到这一点。

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

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>