1

I'm learning Angular JS, so I combined to exercises together, and my app looks like this :

<!DOCTYPE html>
<html>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>

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

<div ng-app="myApp" ng-controller="myCtrl">

First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}

</div>

<script>
var app = angular.module('myApp', []).controller('myCtrl', function($scope)
{
    $scope.firstName= "John";
    $scope.lastName= "Doe";
});
</script>

<div ng-app="2nd" ng-init="quantity=1;cost=5">

<p>Total in dollar: {{ quantity * cost }}</p>

</div> 

</body>
</html>

But the 2nd part is not showing "5", if I put it in a file by itslef, it will work correctly, why ?

Frank
  • 30,590
  • 58
  • 161
  • 244

1 Answers1

3

1) Using angular.bootstrap

As per the AngularJS manuals, only one angularjs app can be auto-bootstrapped for one html document. The first ng-app found in the doc will be used, to run the second ng-app (="2nd"), you need to manually bootstrap (angular.bootstrap). Check this out for refernce https://docs.angularjs.org/api/ng/directive/ngApp .

<div ng-app = "myApp"  ng-controller="myCtrl">>

</div>
<div id = "second">

</div>

and the corresponding js file,

angular.bootstrap(document.getElementById("second"), ['2nd']);

2) Using multiple modules

You can combine the two modules and make it into one ng-app to a superior element

akashrajkn
  • 2,295
  • 2
  • 21
  • 47