Reputation: 1
I am doing a AngularJS tutorial which comprised of an HTML file and a simple JS script to provide simple Angular functionality. The following is the HTML file.
<!DOCTYPE>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src='main.js'></script>
<head>
<title> Angular Practice </title>
</head>
<body ng-app='learningAngular' ng-controller='myCntr'>
<input type="text" ng-model='name'> <br>
<div ng-bind='name' ng-click='alertMe()'></div>
<button ng-click='alertMe()'>Alert Me Angular</button> <br>
<div ng-show='willShow'> Show this!! </div>
<button ng-click='toggleShow()'> Show </button>
<div ng-hide='willShow'> using ng-hide! </div>
<ul ng-repeat='puppy in doggos'>
<li> {{ puppy }} </li>
</ul>
<ul ng-repeat='(student, grade) in grades'>
<li> {{ student }}, {{ grade }} </li>
</ul>
</body>
</html>
The script, main.js, which lies in the same folder, looks like this:
var app = angular.module('learningAngular', []);
app.controller('myCntr', ['$scope', function($scope) {
$scope.name = 'Josephine';
$scope.alertMe = function() {
alert("Congrats!");
};
$scope.willShow = true;
$scope.toggleShow = function() {
$scope.willShow = !$scope.willShow;
};
$scope.doggos = ['rex', 'fido', 'rover'];
$scope.grades = {
Max: 'A',
Joan: 'B',
Jay: 'C'
};
}]);
I am very confused because when I have the Angular module/controller in the script file (main.js) in the same folder, Angular no longer works. When I move the script into index.html, it works perfectly fine. I have tried messing around with the src='main.js' to see if that was the problem, and couldn't find anything wrong with it.
Upvotes: 0
Views: 231
Reputation: 962
Your <script>
tag should be inside your <head>
or <body>
tag. That might be why it's not picking it up.
Something like this should work:
<!DOCTYPE>
<html>
<head>
<title> Angular Practice </title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="main.js"></script>
</head>
<body ng-app='learningAngular' ng-controller='myCntr'>
...
</body>
</html>
The old convention was to put scripts at the end of the <body>
tag, but since we're working with a Javascript framework that is responsible for rendering the view, that convention doesn't make sense anymore.
Upvotes: 1