Nitesh
Nitesh

Reputation: 97

Controller not loading if javaScript containing controller code is added dynamically to HTML dom

Here is a example code: I have following code at the end of html body

<script type="text/javascript">
    var js = document.createElement("script");
    js.src = "forms/dynamicForms/sampleFormController.js";
    document.body.appendChild(js);
    angular.bootstrap(document, ['MyApp']);
</script>

When I run my app, sampleFormController is not found, if I inspect body tag in Chrome, script is added as a child tag to body tag.

where as when I modify code and add timeout it works

<script type="text/javascript">
    var js = document.createElement("script");
    js.src = "forms/dynamicForms/sampleFormController.js";
    document.body.appendChild(js);
    setTimeout(myFunction, 2000);
    function myFunction() {
    angular.element(function() {
        angular.bootstrap(document, ['MyApp']);
      });
    }
</script>

Is there a way to make my first code to work without adding timeout?

Upvotes: 0

Views: 69

Answers (1)

Sᴀᴍ Onᴇᴌᴀ
Sᴀᴍ Onᴇᴌᴀ

Reputation: 8297

You can set the onload property of the script tag to myFunction(). Refer to the MDN page on HtmlScriptElement for more information and an example similar to the modified code snippet below. Also, see it utilized in this example plunker.

Similarly, you can set the onerror property to a function for handling the case when an error occurs. And because this code is asynchronous, you could use Promises- see this example.

<script type="text/javascript">
    var js = document.createElement("script");
    js.src = "http://elliott.andrewz.org/data/sampleController.js";
    document.body.appendChild(js);
    js.onload = myFunction;
    function myFunction() {
        angular.element(function() {
            angular.bootstrap(document, ['MyApp']);
      });
    }
</script>

Upvotes: 2

Related Questions