0

I am working on an application that utilizes both Jquery and AngularJS includes, however Angular does not seem to execute after Jquery has included a file that has AngularJS markup. Jquery is including the "top_nav.html" template and inside this template there lives a angluar ng-include calling cart.html". I need to figure out how to get the angular code to execute after being included by jQuery.

<div id="topNav"></div>

<script> 
  //outside the document ready statment
  $('#topNav').load('includes/top_nav.html'); 
<script>

top_nav.html:

<div>
 ... 
  <div ng-controller="shoppingCart"
   class="shopping-cart"ng-include="'includes/cart.html'"></div>
</div>
Coded Container
  • 863
  • 2
  • 12
  • 33
  • Possible duplicate of [How to bind an AngularJS controller to dynamically added HTML?](http://stackoverflow.com/questions/20651578/how-to-bind-an-angularjs-controller-to-dynamically-added-html) –  Jan 03 '17 at 20:33

1 Answers1

1

The jquery load does an ajax request. When the ajax is resolved, the angular have already been bootstrapped (assuming you use ng-app directive), so the html chunk that have been dynamically loaded was not bootstrapped by angular.

So, I guess that on the callback of the jquery load, you need to manually bootstrap angular passing <div id="topNav"></div> as the context. Something like this:

var topNav = $( "#topNav" );
topNav.load( "includes/top_nav.html", function() {
  angular.bootstrap(topNav.find("> div")[0], ['topNavAngularModule']);
});

Note: I'm not sure, sorry, I haven't tested it, but I think it might only work if #topNav is located outside ng-app.

falsarella
  • 12,217
  • 9
  • 69
  • 115
  • Try this: `angular.bootstrap(topNav.find("> div")[0], ['topNavAngularModule']);`, but I think it might only work if jquery is loading html outside `ng-app`. If that doesn't work, try the [possible duplicate question](http://stackoverflow.com/q/20651578/1064325) provided by Professor Allman. – falsarella Jan 03 '17 at 21:04
  • 1
    Got this to work by removing ng-app from the website to prevent auto loading. Thanks! – Coded Container Jan 03 '17 at 21:06
  • @CodedContainer Awesome! Just an observation: now, angular will only bootstrap the page _after_ the jquery loads the `top_nav.html`, decreasing loading performance a little bit. I hope it won't be an issue to your case. – falsarella Jan 03 '17 at 21:10
  • Awesome, I was running into a problem were it was not loading the rest of my Angular app, but then I just added another ng-app where needed and the rest of the page works. Thanks for your help! – Coded Container Jan 04 '17 at 15:03