意外地多次加载angularjs会导致奇怪的行为

时间:2013-12-31 21:06:58

标签: javascript angularjs ng-repeat

由于Angular.js的动态加载实例,我发现ng-repeat会将显示的项目数量多维数据集的问题。

以下代码演示了此问题:

<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>

如何防止Angular的JS文件被多次加载,但是仍然可以动态地向页面添加脚本引用?

鉴于我仍然需要动态地将脚本文件引用添加到我的页面,我该怎么做才能防止上述问题发生?

1 个答案:

答案 0 :(得分:1)

可以使用window.angular包装angularjs的加载代码,如下所示:

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

或者如果你碰巧使用了角度的本地副本:

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

这样可以避免无意中加载角度两次,从而产生意外和无声的副作用。