0

I have a simple javascript code that dynamically adds HTML content to a div tag.

function addData(id,title,title_data){

  var htmlcode='';

  htmlcode+=`<h1> Title: `+title+` </h1> <div ng-app="">
              <input ng-model="model`+title+id`" ng-init="model`+title+id+'='+\'`+title_data+`\'`"    >`+


`<p ng-bind="model`+title+id`"> </p>`;



   return htmlcode;
}

Then i simply use it like this:

$('#someDiv').html(addData(1,'Some Title','Some title data'));

The html works well and displays the desired dynamic content. But the angular bindings didn't work. The copy pasted version of the rendered html from web browser works well including the bindings but the dynamic one does not. What seems to be the problem?

17
  • I think that might because the bindings have already been created for the existing entities during page load. And you are trying to add new bindings later on in your code. Commented Sep 8, 2017 at 23:03
  • 1
    Firstly, $('#someDiv') is jQuery code, not angular; trying to use angular in this way is highly irregular, and not recommended. This seems to indicate that perhaps your overall app design isn't fully embracing angular. If you are able to re-factor your app to remove jQuery and still find that you need HTML strings like this (rather than angular templates or simillar), then, and only then, should you look at how to compile dynamic expressions. Commented Sep 8, 2017 at 23:11
  • Beyond my last comment, the actual angular code you are using here is a very old syntax, for angular version 1.2, which is more than 3 years old. Newer releases of angular will not work when ng-app==="". Commented Sep 8, 2017 at 23:17
  • Any code that modifies DOM should be implemented as directive. You mixed JQuery DOM manipulation with angular. The angular data binding will not work here until you tell angularjs to compile and re run digest cycle. Commented Sep 8, 2017 at 23:25
  • 1
    the main problem here is that angular is initialized on page load; adding an ng-app to the DOM after the page is finished loading doesn't tell angular that it should go looking for that element. if you are insistent that this is the only way you can develop this app, you will be responsible for manually bootstrapping the app (docs.angularjs.org/guide/bootstrap), but this generally means you need to know a bit more about how the framework works, and after you spend time learning about it, you'll realize how much of a terrible idea this really is. Commented Sep 10, 2017 at 3:11

1 Answer 1

0

You are not using the ng-app name in the declared dynamic html code.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.