Search code examples
angularjsjson2html

using ng-model with dynamically generated HTML form


I have a JSON object that I am converting to HTML using json2html library. This HTML form has a username and password field. I need to pass the values of username and password entered to the backend for authentication. This form was working absolutely fine when the HTML was static, since now, HTML is generated dynamically ng-model for text fields is not working at all. Any help in eliminating this issue would be appreciated. Thanks


Solution

  • You need to use $compile. Angular does not know about the html you just dumped onto the page (unless you did with Angular templating). You need to register the new dom with Angular and a specific scope.

    Something like this:

    $('#container').append($compile($(HTMLString)));
    

    Learn all about it -> $compile


    However I would recommend not adding the html outside of Angular. You can do so a number of ways including using $templateCache.

    $templateCache.put('myForm', HTMLString);
    

    then

    Learn all about it -> $templateCache, ngInclude


    You could also write a directive, or even not dynamically make HTML, but rather attach the parsed JSON directly to $scope and do a clever ng-repeat.