-1

I am trying to delay the module creation, but it doesn't work (I am using Chrome). Here is my code TRY THE JSFIDDLE

<!doctype html>
<html>
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.min.js"> </script>
</head>
<body>
<div ng-controller="MyCtrl">
    Hello, {{name}}!
</div>
<script>
    //initApp();
    setTimeout(initApp, 1000);

    function initApp() {
        var myApp = angular.module('myApp', []);
        myApp.controller('MyCtrl',
            function($scope) {
                $scope.name = 'Superhero';
            });
    }
</script>
</body>
</html>

If I remove the setTimeout and simply call initApp(), then it works. Can anyone explain why?

I am trying to embed an angular app into a page, and I am not allowed to add script tags to the HEAD. So I have to figure out some way to postpone the angular module initialization until after the angular.min.js is loaded and parsed.

John Henckel
  • 10,274
  • 3
  • 79
  • 79

2 Answers2

2

It's not how you do it in angular way.

First i don't see any ng-app tag so your controler won't ever be called.

Second in order to delay the bootstrapping (and not using ng-app tag) you use angular.boostrap :

 //initApp();
setTimeout(initApp, 1000);
var myApp = angular.module('myApp', []);
    myApp.controller('MyCtrl',
        function($scope) {
            $scope.name = 'Superhero';
        });
function initApp() {
   angular.bootstrap('myApp');
}

For dynamic loading of javascript file see : lazy loading javascript the second point of the author of the post should do the job.

Community
  • 1
  • 1
Walfrat
  • 5,363
  • 1
  • 16
  • 35
  • Perfect. This is how I solved it in the end. However in my `initApp` I test `if (angular == null)` then setTimeout again and return. Also I use 100 ms. Now I can embed angular on just about any page, without any worry about the order of the scripts. – John Henckel Jul 13 '16 at 13:42
1

There is no need to use setTimeout. Browsers parse the JavaScript in the order they are declared in the HTML unless the async attribute is used.

Martin
  • 15,820
  • 4
  • 47
  • 56