如何拆分Angular多模块页面的文件?

时间:2014-10-30 15:26:15

标签: javascript angularjs twitter-bootstrap

我已经按照这个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>

结果:第二个模块不起作用。

内联script

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

结果:它有效。

我错过了哪些想法?

1 个答案:

答案 0 :(得分:2)

在第一种情况下,您在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函数包装成文档就绪,并将bootstrap.js脚本留在head部分:

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