Search code examples
javascriptangularjsangular-ngmodel

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


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.


Solution

  • 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>