Gabe Rogan Gabe Rogan - 21 days ago 9
Javascript Question

Why doesn't AngularJS initialize with inline <script>?

http://codepen.io/krabbypattified/pen/oYxmKz

View above Codepen. The Chrome DevTools console returns Error: [$injector:modulerr]. The same error occurs when script area is commented.

However, when script area is commented and the (identical) JS section is uncommented, Angular works fine with no errors. Why does this happen??

Note: I have a large application and isolated the bug to this phenomenon. I'm using a Prepros server and I'm getting this same annoying $injector error.

<div ng-app="testApp">
<div ng-controller="testController">
<h1>{{title}}</h1>
</div>
</div>

<script>
var app = angular.module('testApp',[]);

app.controller('testController', function($scope){
$scope.title = "Hello, World!";
});
</script>

Answer

Codepen adds the code after the HTML, so the script you have initializing Angular won't have access to angular. If you change to this it will work.

<div ng-app="testApp">
  <div ng-controller="testController">
    <h1>{{title}}</h1>
  </div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<script>
var app = 
    angular.module('testApp', []).controller('testController', function($scope){
  $scope.title = "Hello, World!";
});
</script>
Comments