AngularJS Multiple ng-app within a page

ghz 1years ago ⋅ 1242 views

Question

I have just started learning Angular JS and created some basic samples however I am stuck with the following problem.

I have created 2 modules and 2 controllers.

shoppingCart -> ShoppingCartController
namesList -> NamesController

There are associated views for each controller. The first View renders fine but second is not rendering. There are no errors.

http://jsfiddle.net/ep2sQ/

Please help me solve this issue.

Also is there any possibility to add console in View to check what values are passed from Controller.

e.g. in the following div can we add console.log and output the controller values

<div ng-app="shoppingCart" ng-controller="ShoppingCartController">
</div>

Answer

So basically as mentioned by Cherniv we need to bootstrap the modules to have multiple ng-app within the same page. Many thanks for all the inputs.

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 src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>

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