1

I have a file index.html with the following code:

<div ng-include="'fragment-1.html'"></div>

The code of fragment-1.html:

<b>Inside Fragment 1</b>
<script type="text/javascript">
    alert("Inside Fragment 1");
</script>

When I load index.html into the browser, output is:

Inside Fragment 1

The DOM has the <script> tags but the alert is not shown.

My hypothesis:

Because the DOM loads first along with the Angular modules and then Angular checks and binds the data(in this case, fragment-1.html file content) to the view(index.html), it just adds the elements of fragment-1.html in DOM. To execute the JS inside fragment-1.html, we should create a hack for it. Am I right in this explanation? Or is there something else that I may be missing?

1

3 Answers 3

4

I had to load jQuery before loading Angular. The explanation is in the link specified above. Explanation: script not running in templateurl

To include another partial HTML file in your parent HTML file, one can also use Angular directives, depending on the situation. See this answer for when to use ng-include and when to use directives: https://stackoverflow.com/a/24172025/3132646

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

Comments

1

You don't need to hack. Angular gives you a neat and simple solution to what you want to achieve with your code.

Controller

.controller('fragmentOneCtrl', function ($scope) {
    alert('"Inside Fragment 1"');
})

View

<div ng-repeat="go in ['go', 'gogo']" ng-include="'includeThis'">

</div>

<script type="text/ng-template" id="includeThis">
    <div ng-controller="fragmentOneCtrl">

    </div>
</script>

3 Comments

This works perfectly when the code is in index.html itself. I want to include a separate file fragment-1.html whose javascript code should run when it is included in index.html.
Ok but is it not an exact use case for directive?
Thanks for pointing me to directives. Still learning Angular. Was still unable to execute JS inside fragment-1.html using directives. Found my answer here: http://stackoverflow.com/questions/32048046/script-not-running-in-templateurl
0

You may want to use $sce.trustAsHtml before injecting the resource in html

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.