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

妖精的绣舞 提交于 2019-12-07 08:45:59

问题


I'm having a simple html form like this

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

And now I want to add an input field from 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);
}

The input field also get's generated as expected

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

but the ng-model between this input field and $scope.test is not working.


回答1:


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>


来源:https://stackoverflow.com/questions/31741195/how-to-add-ng-model-to-an-at-runtime-created-html-object

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