简体   繁体   中英

Using angular in partial pages loaded into a main page

I have a single page app. The main index page has <div> section that loads different partial pages depending on user actions. Each partial page has different functionality.

For example, here is how my main page looks like. Pretty basic:

 <html> 
 <head>...</head>
 <body>
 ...
 <div id='content-body'>
 ...
 </body>
 </html>

The partial pages get loaded into the content-body <div> via jQuery like so:

$('#content-body').load(filename, function (....) ...);

Some partial pages are simple forms and have javascript behind it. Again, pretty basic:

<form id="ABC">
 <div class="row">
   <fieldset class="form-group col-sm-3">
   ...
</form>
<script src="scripts/abc.js" />

Problem: For some partial pages (not all), I'd like to use angular. I've created something like so:

<script src="scripts/angular.js"></script>
<script src="scripts/app.js"></script>
<div ng-app="myApp" ng-controller="myController">
    <p>Angular TEST: {{ 1 + 2 }}</p>
    <form id="DEF">
    ...
    </form>
</div>
<script src="scripts/def.js"></script>

This does not work. From what I can tell, it is because angular needs to compile the whole page and wont work on just a partial page. Is this correct? Is there a way I can get angular to work in a partial page only like this?

Also - I cannot apply angular to the whole app / main index page. It is not an option for me.

I will post a sample below but here are the steps. You need to basically manually bootstrap the app. To bootstrap you need the element, and the module. So in my example I start with an empty div with an id of content-here. When the dom loads I basically insert a mini angular app and then manually call the bootstrap function. If you can in advance load the scripts i recommend you do it. If you have to wait to load them let me know and I'll update the fiddle.

<div id='content-here'> </div> 

Then you would setup your angular app however you chose.

angular.module('myApp', []);
angular.module('myApp').controller('NixCtrl',NixCtrl);


function NixCtrl($scope){
  $scope.test = "Hello there Angular!"
}

The last step is to setup an event listener or some block of code to add the angular app to the dom, and then call the bootstrap function:

document.addEventListener("DOMContentLoaded", contentLoaded);

function contentLoaded(){
  var template = ' <div ng-app="myApp"><div ng-controller="NixCtrl">{{test}} </div> </div>';

  $('#content-here').html(template);
   angular.bootstrap($('#content-here'), ['myApp']);
}

http://jsfiddle.net/ncapito/wzdf9k6d/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM