1

I use ajax to dynamically load part of page in a Sails project views/homepage.ejs. The controller is "food", "show" is one action of "food", so I have a file /views/food/show.ejs. So by using Ajax load food/show, will load show.ejs.

$('#outerDiv').load("food/show",function(responseTxt,status,xhr){
  if(status!=="error"){
     alert("BOOT...");
     //bootstrap angular
     angular.bootstrap($("#outerDiv"));
  }
});

The content of show.ejs is like this:

<script>
  alert("LOAD..");
  var app = angular.module("myApp",[]);
  app.controller("myCtrl",function (){
    this.numInStock= 10;
  })
</script>
<div ng-app="myApp" ng-controller="myCtrl">
<p>The number in stock is: {{numInStock}}</p>
</div>

But the angular in that loaded page still cannot work, even I try to manually bootstrap angular for the new loaded page.

Alert(LOAD...) comes first, then Alert(BOOT...) comes next, while I found the new page was already rendered like "The number in stock is: {{numInStock}}". Obviously, it's wrong, I want it to be "The number in stock is: 10".

Chrome console gives an error:

Uncaught Error: [ng:btstrpd] http://errors.angularjs.org/1.2.26/ng/btstrpd?p0=%26lt%3Bdiv%20id%3D%22subPage%22%26gt%3B
Travis Webb
  • 14,688
  • 7
  • 55
  • 109
user2321728
  • 1,293
  • 1
  • 12
  • 17

2 Answers2

3

You need to remove the ng-app from your HTML. Your Angular page is initialized on page load because you've added it to the HTML also.

  1. Remove the ng-app from your HTML
  2. Change the bootstrap code to:

angular.bootstrap($('#outerDiv'), ['myApp']);

More info: https://docs.angularjs.org/guide/bootstrap

But still, if the ajax page takes a few seconds to load you'll still see the curly braces. To fix this you can use i.e. ng-bind instead.

<p>The number in stock is: <span ng-bind="numInStock"></span></p>

Plnkr example: http://plnkr.co/edit/c6Y0kQulzvLbI2iCp7HZ?p=preview

Dieterg
  • 16,118
  • 3
  • 30
  • 49
  • I don't want to remove ng-app in show.ejs, because only show.ejs is bind to angular app, and homepage.ejs should stay away from angular. And I tried angular.bootstrap($('#outerDiv'), ['myApp']), not working... – user2321728 Feb 09 '15 at 09:17
  • When using bootstrap you don't need to use ng-app. You don't have to add it to any other page.. – Dieterg Feb 09 '15 at 09:20
  • Thanks for your demo. I finally found the reason. It's because $('#outerDiv').load("food/show"), this page contains not only – user2321728 Feb 09 '15 at 12:44
1

Your selector is missing the #:

angular.bootstrap($("#outerDiv"));

You could also use this as it will reference the same element and save another request to the DOM.

angular.bootstrap($(this));
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339