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?

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
chaudharyp
  • 3,394
  • 3
  • 26
  • 42
  • Possible duplicate of [how can i load javascript file along with ng-include template](http://stackoverflow.com/questions/20087274/how-can-i-load-javascript-file-along-with-ng-include-template) – gyc Dec 08 '15 at 12:08

3 Answers3

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

Community
  • 1
  • 1
chaudharyp
  • 3,394
  • 3
  • 26
  • 42
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>
Chris Hermut
  • 1,708
  • 3
  • 17
  • 32
  • 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. – chaudharyp Dec 08 '15 at 16:37
  • 1
    Ok but is it not an exact use case for directive? – Chris Hermut Dec 08 '15 at 20:08
  • 1
    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](http://stackoverflow.com/questions/32048046/script-not-running-in-templateurl) – chaudharyp Dec 09 '15 at 06:25
0

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