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

自闭症网瘾萝莉.ら 提交于 2019-12-05 16:21:11

Important: You should not make dom manipulation in a cotroller, you need to use a directive to do that.

That said, even in a directive if you are creating a dynamic element you need to compile it to have angular behavior applied to it.

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!