Question

Due to dynamically loaded instances of Angular.js, I'm seeing an issue where ng-repeat will cube the number of items displayed.

The following code demonstrates the issue:

<html ng-app="brokentable">
<head>
    <title>Broken Angular Table</title>

  <!-- the following are dynamically added by other code -->
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js"></script>

   <script type="text/javascript">
        var app = angular.module('brokentable', []);

        app.controller('BrokenTable', function($scope) {
            $scope.headings = ['One', 'Two', 'Three'];
            $scope.fillings = [[1, 2, 3], ['A', 'B', 'C'], [7, 8, 9]];
        });
  </script>
</head>
<body ng-controller="BrokenTable">
    <table>
    <tr>
      <th ng-repeat="heading in headings">{{heading}}</th>
    </tr>
    <tr ng-repeat="filling in fillings">
      <td ng-repeat="fill in filling">{{fill}}</td>
    </tr>
  </table>
</body>
</html>

How do I prevent Angular's JS file from being loaded multiple times, but still enable dynamically adding script references to the page?

Given that I still have the need to add the script file references to my page dynamically, what can I do to keep the issue demonstrated above from happening?

Was it helpful?

Solution

It is possible to wrap your loading code for angularjs using window.angular as follows:

  <script>
    if (!window.angular) {
      document.write('<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js"><\/script>');
    }
  </script>

or if you happen to be using a local copy of angular:

  <script>
    if (!window.angular) {
      document.write('<script src="angular.js"><\/script>');
    }
  </script>

This way you can avoid inadvertently loading angular twice which results in unexpected and silent side effects.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top