2014-10-30 108 views
1

我已經按照這個answer在AngularJS中創建了多個模塊,但是當我將Angular代碼拆分爲多個js文件時,它不起作用。如何分割Angular多個模塊頁面的文件?

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> 

結果:它的工作原理。

任何想法,我已經錯過了?

回答

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.js腳本:

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

的Git它謝謝。 – laukok 2014-10-30 15:50:25