Wednesday, June 10, 2015

Multiple Applications (Modules) and Controllers in AngularJS

I have just started learning Angular JS and I am stuck with the following problem.

I have created 2 ng-app and 2 ng_controller's.

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

<html>
<script src= "angular.min.js"></script>
<body>

<p>Try to change the names.</p>

<div  id="div1" ng-app="myApp" ng-controller="myCtrl" ng-init="firstName1='John'">

First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
<p>Name: <input type="text" ng-model="name"></p>
<p ng-bind="name"></p>
<p>"ng-bind" used - The name is <span ng-bind="firstName1"></span></p>
<p>"{{firstName1}}" used - The name is {{firstName1}}</p>
</div>
<div id="div2" ng-app="namesApp" ng-controller="namesCtrl">
<ul>
<li ng-repeat="x in names">
{{ x.name + ', ' + x.country }}
</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName= "John";
$scope.lastName= "Doe";
});

angular.module('namesApp', []).controller('namesCtrl', function($scope) {
$scope.names = [
{name:'Jani',country:'Norway'},
{name:'Hege',country:'Sweden'},
{name:'Kai',country:'Denmark'}
];
});
</script>
</body>
</html>

Solution:

        Technically possible to have several applications per page, only one ng-app directive will be automatically instantiated and initialized by the Angular framework. we need to bootstrap the modules to have multiple ng-app within the same page.

To overcome this issue by using the angular.bootstrap() directly.

place below line of code before the </script> tag:
angular.bootstrap(document.getElementById('div2'),['namesApp']);


No comments:

Post a Comment