Running a basic Angular example

Hi,

I am having trouble with this basic example of Angular and just can’t see what i am doing wrong. I would appreciate if anyone could have a glance at it. Thanks.

index.html

<!DOCTYPE html>
<html ng-app>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
  <script src="script.js"></script>
</head>
<body>
  product is {{3*6}}
  <div ng-controller="MainController">
  {{message}}
  </div>
</body>
</html>

script.js

var MainController = function($scope){
  $scope.message = "Hello to you all";
};

script.js and index.html are in the same folder.

Also it is strange that when
product is {{36}}
is moved inside the div with ng-controller it doesn’t work, I get {{3
6}} not 18.

Thanks,

Hi @ofeyofey,

You need to change a couple things to get your example up and running:

  • Create an Angular module, and attach your controller function to it:
var MainController = function($scope){
  $scope.message = "Hello to you all";
};

angular
  .module('myApp', [])
  .controller('MainController', MainController);
  • Add the name of your module to the ng-app attribute:
<!DOCTYPE html>
<html ng-app="myApp">

Now the message will be output, and any expressions (eg. {{3*6}}) will be executed inside your MainController div.

Hi,
Thanks for your reply. Your suggestions make a lot more sense. I made those changes but still the same output.

index.html

<!DOCTYPE html>
<html ng-app="myApp">
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-controller="MainController">
  product is {{3*6}}
  {{message}}
</body>
</html>

script.js

angular
  .module('myApp', [])
  .controller('MainController', MainController);

var MainController = function($scope){
  $scope.message = "Hello to you all";
};

Output in browser is,

product is {{3*6}} {{message}}

I tried putting the angular. chaining module code before and then after the controller function in case that made a difference.

Also I am sure that the page is refreshing, because I changed the 6 to a 7 and this change is reflected in the browser output.

Following a tutorial from here

Thanks

Ah it works now!

After your additions, i had forgot to include the src=“script.js”

Thanks very much for your help.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.