由于动态加载了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>
鉴于我仍然需要将脚本文件引用动态添加到我的页面,我该怎么做才能防止上述问题的发生?
可以使用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] 删除。
我来说两句