Search code examples
javascripthtmlangularjshtml-sanitizing

How to add input forms dynamically in Angular JS


I want to change the form inputs dynamically , and i have tried doing it using ng-bind-html , but only label is getting displayed , text box doesn't appears on the DOM. Here what has to be written inside ctrl.content depends upon the values from the server.

Note

type value will be coming from server , and it can be dynamic

HTML

<div ng-bind-html="ctrl.content">

Controller

function myCtrl(type) {
   var ctrl = this;

   switch (type) {
     case 1:
      ctrl.content = " <div> Input : <input type=\"text\" > </div> ";
       break;
       case 2:
        ctrl.content = " <div> Input : <input type=\"textarea\" > </div> ";
         break;
     default:


   }

Dom Element :

<div class="padding ng-binding ng-scope" ng-bind-html="addMeassurments.content"> <div> Input :  </div> </div>

Solution

  • First, your assignment is all wrong

    ctrl.content = " <div> Input : <input type=\"text\" > </div> ";
    

    You should be assigning the markup to a $scope property. e.g.

    $scope.content = " <div> Input : <input type=\"text\" > </div> ";
    

    Secondly you should use the $sce service to sanitize the html. Here's a plnkr where this code demonstrates the intended behavior

    var app = angular.module('plunker', []);
    
    app.controller('Ctrl', function($scope, $sce) {
      $scope.name = 'World';
      var ctrl = this;
      $scope.click = function myCtrl(type) {
        switch (type) {
          case 1:
            $scope.content = $sce.trustAsHtml("<div> Input : <input type=\"text\" > </div> ");
            break;
          case 2:
            $scope.content = $sce.trustAsHtml(" <div> Input : <textarea></textarea> </div> ");
            break;
          default:
        }
      }
    });
    

    Note also that I changed your markup from input type="textarea" to a textarea element.