gpt4 book ai didi

javascript - 如何为 Angular 多模块页面拆分文件?

转载 作者:行者123 更新时间:2023-11-30 17:12:47 25 4
gpt4 key购买 nike

我关注了这个 answer用于在 AngularJS 中制作多个模块,但是当我将 Angular 代码拆分为多个 js 文件时它不起作用。

Bootstrap.js

angular.bootstrap(document.getElementById("App2"),['namesList']);

HTML

<html>
<head>
<script src="components/angular/angular.js"></script>
<script src="scripts/module1.js"></script>
<script src="scripts/module2.js"></script>
<script src="scripts/bootstrap.js"></script>
</head>
<body>
<div id="App1" ng-app="shoppingCart" ng-controller="ShoppingCartController">
<h1>Your order</h1>
<div ng-repeat="item in items">
<span>{{item.product_name}}</span>
<span>{{item.price | currency}}</span>
<button ng-click="remove($index);">Remove</button>
</div>
</div>

<div id="App2" ng-app="namesList" ng-controller="NamesController">
<h1>List of Names</h1>
<div ng-repeat="_name in names">
<p>{{_name.username}}</p>
</div>
</div>
</body>
</html>

结果:第二个模块不工作。

内联脚本

<html>
<head>
<script src="components/angular/angular.js"></script>
<script src="scripts/module1.js"></script>
<script src="scripts/module2.js"></script>
</head>
<body>
<div id="App1" ng-app="shoppingCart" ng-controller="ShoppingCartController">
<h1>Your order</h1>
<div ng-repeat="item in items">
<span>{{item.product_name}}</span>
<span>{{item.price | currency}}</span>
<button ng-click="remove($index);">Remove</button>
</div>
</div>

<div id="App2" ng-app="namesList" ng-controller="NamesController">
<h1>List of Names</h1>
<div ng-repeat="_name in names">
<p>{{_name.username}}</p>
</div>
</div>
<script>
angular.bootstrap(document.getElementById("App2"),['namesList']);
</script>
</body>
</html>

结果:有效。

有什么我遗漏的想法吗?

最佳答案

在第一种情况下,您在加载 dom 之前执行 bootstrap.js。这应该有效:

<html>
<head>
<script src="components/angular/angular.js"></script>
<script src="scripts/module1.js"></script>
<script src="scripts/module2.js"></script>
</head>
<body>
<div id="App1" ng-app="shoppingCart" ng-controller="ShoppingCartController">
<h1>Your order</h1>
<div ng-repeat="item in items">
<span>{{item.product_name}}</span>
<span>{{item.price | currency}}</span>
<button ng-click="remove($index);">Remove</button>
</div>
</div>

<div id="App2" ng-app="namesList" ng-controller="NamesController">
<h1>List of Names</h1>
<div ng-repeat="_name in names">
<p>{{_name.username}}</p>
</div>
</div>
<script src="scripts/bootstrap.js"></script>
</body>
</html>

或者,您可以将 bootstrap 函数包装到 document ready 中,并将 bootstrap.js 脚本留在 head 部分:

angular.element(document).ready(function() {
angular.bootstrap(document.getElementById("App2"),['namesList']);
});

关于javascript - 如何为 Angular 多模块页面拆分文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26657025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com