简体   繁体   中英

Load whole AngularJS page by AJAX

I need to load a whole legacy page including some AngularJS by AJAX into our new page.

At first it didn't work at all, I just got the plain AngularJS markup eg

Rank         ID
{{$index+1}} {{player.playerid}}

But then I found this stackoverflow thread with this demo , which uses $compile and works perfectly fine for the given example in the thread. So I tried to get it running with my code and now I get following error message

Error: [ng:areq] Argument 'HighscoreCtrl' is not a function, got undefined

I use $.get to get the whole Angular-Page and filter the response for the div holding all the content (angular markup, module and controller), which then gets put into the div#mainContent .

jQuery get:

$.get(link, function(data) {

  var temp = $(data);

  var links = temp.filter('link');
  var scripts = temp.not('div').not('link').not('meta').not('title');
  var body = temp.filter('#test123');

  console.log(body);
  $("#mainContent").html(
      $compile(
        body
      )($scope));
    $scope.$apply();
  });

body contains:

<div id="test123" ng-app="indexApp">
  <div class="container" ng-controller="HighscoreCtrl">

    <table class="table">
      <tr>
          <th>Rank</th>
          <th>ID</th>
      </tr>
      <tr ng-repeat="player in players">
          <td>{{$index+1}}</td>
          <td>{{player.playerid}}</td>
      </tr>
    </table>
  </div>
  <script type="text/javascript">
    var angularModule = angular.module('indexApp', []);

    angularModule.controller('HighscoreCtrl', function($scope, $http){
        $scope.players = [
                    { playerid: "Joe#2293"},
                    { playerid: "Joe#0815"}
                ];
    });
  </script>
</div>

I already tried to split the angular part and include the module and controller before compiling the markup, but that didn't work either.

Is what I'm trying to do even possible?

Here is a simple example I created to test my code: plnkr-Demo

It looks like you have not included the js file for your controller since you are just pulling in the body. The scrip reference is probably in the head section. You will need to include the link to that js file either in the body or dynamically adding it back in.

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