主頁 » AngularJS » [AngularJS] $rootScope & $scope 的差別

[AngularJS] $rootScope & $scope 的差別

官網說明如下:

  1. Every application has a single root scope. All other scopes are descendant scopes of the root scope.
  2. The location where the root scope is attached to the DOM is defined by the location of ng-app directive.

意思是說,在被宣告 ng-app 的 DOM 範圍內,只有一個 root scope 即 $rootScope。

言下之意,在<html></html>內可以有多個 ng-app。
第一個 ag-app 會自動被導引對應到 module 內,其餘要使用 angular.bootstrap 這個方法來做,範例如下:(看有綠色打勾的sample code)
http://stackoverflow.com/questions/18571301/angularjs-multiple-ng-app-within-a-page

<html>
<head>
  <script src="angular.min.js" type="text/javascript"></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">

{{_name.username}}</div>
</div>
<script type="text/javascript">
    var shoppingCartModule = angular.module("shoppingCart", [])
    shoppingCartModule.controller("ShoppingCartController",
        function($scope) {
            $scope.items = [
                {product_name: "Product 1", price: 50},
                {product_name: "Product 2", price: 20},
                {product_name: "Product 3", price: 180}
            ];
            $scope.remove = function(index) {
                $scope.items.splice(index, 1);
            }
        }
    );
    var namesModule = angular.module("namesList", [])
    namesModule.controller("NamesController",
        function($scope) {
            $scope.names = [
                {username: "Nitin"},
                {username: "Mukesh"}
            ];
        }
    );
    angular.bootstrap(document.getElementById("App2"),['namesList']);
  </script>
</body>
</html>

發表留言