If I place the <script>
containing the js code at the bottom of the <body>
, the 2nd div's expression is evaulated. If it's at the top of the <body>
or in the <head>
, it's not evaulated.
Why is this?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<!--If the script is here, the dvSecond div's expression is not evaulated-->
</head>
<body>
<!--If the script is here, the dvSecond div's expression is not evaulated-->
<div ng-app="myApp" id="dvFirst" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>
<div id="dvSecond" ng-controller="myCtrl1">
{{ firstName1 + " " + lastName1 }}
</div>
<!--If the script is here, the dvSecond div's expression IS evaulated-->
<script>
var dvSecond = document.getElementById('dvSecond');
angular.element(document).ready(function() {
angular.bootstrap(dvSecond, ['myApp1']);
});
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
var app1 = angular.module("myApp1", []);
app1.controller("myCtrl1", function($scope) {
$scope.firstName1 = "John1";
$scope.lastName1 = "Doe1";
});
</script>
</body>
</html>
The problem was dvSecond element was fetched before the ready function and it was returning NULL, It should be inside the angular.element(document).ready(function() {});
angular.element(document).ready(function() {
var dvSecond = document.getElementById('dvSecond');
angular.bootstrap(dvSecond, ['myApp1']);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script>
angular.element(document).ready(function() {
var dvSecond = document.getElementById('dvSecond');
angular.bootstrap(dvSecond, ['myApp1']);
});
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
var app1 = angular.module("myApp1", []);
app1.controller("myCtrl1", function($scope) {
$scope.firstName1 = "John1";
$scope.lastName1 = "Doe1";
});
</script>
<!--If the script is here, the dvSecond div's expression is not evaulated-->
</head>
<body>
<!--If the script is here, the dvSecond div's expression is not evaulated-->
<div ng-app="myApp" id="dvFirst" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>
<div id="dvSecond" ng-controller="myCtrl1">
{{ firstName1 + " " + lastName1 }}
</div>
<!--If the script is here, the dvSecond div's expression IS evaulated-->
</body>
</html>