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

呼吸描记器

由于动态加载了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文件多次加载,但仍启用向页面动态添加脚本引用的功能?

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

呼吸描记器

可以使用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>

或者,如果您碰巧正在使用angular的本地副本:

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

这样,您可以避免无意中加载两次角度,而这会导致意外的和无声的副作用。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

UWP在代码后面设置RadioButton.IsChecked会导致奇怪/意外的行为

在Visual Studio中使用文字整数分配的奇怪行为会导致四个意外的编译器错误

D3 sort()导致奇怪的意外行为

尝试grep查找-print0会导致奇怪的行为

向DataFrame添加系列会导致奇怪的行为

Java实例化接口会导致奇怪的行为

反引号作为for循环中的单词会导致奇怪的行为

将Hashmap放入自身会导致奇怪的行为

使用jQuery平滑滚动导航会导致奇怪的行为

从中间件分派动作会导致奇怪的行为

从 JS 更改 css 变量的值会导致奇怪的行为

在 <form> 内嵌套 <button> 会导致意外行为

子集数据帧会导致意外行为

如何阻止div在首页加载时意外加载?

Xcode 7 UITextView奇怪的行为导致视图加载失败

奇怪的angularJs可变行为

奇怪的angularjs路由行为

AngularJS奇怪的行为与模型

冲突的事务导致奇怪的行为

奇怪的启动行为导致崩溃

JSF Servlet导致奇怪的行为

为什么将字符复制到char数组会导致奇怪的行为

在 React Context 中存储和调用函数会导致奇怪的行为

列出生成器(lambdas的向量)列表会导致非常奇怪的行为,即按引用捕获

在 Intersection Observer 的 options 参数中设置 root 属性会导致奇怪的行为

在fix.detectChanges()之后更改Angular中的输入属性会导致奇怪的行为

Monkey 用 Mongoid 在 Rails 中修补数据库模型类会导致奇怪的行为

在列表项上使用翻译时,不透明度会导致奇怪的行为

从片段着色器恢复像素数据会导致意外行为