hello123 hello123 - 2 months ago 8
AngularJS Question

How to use Controllers in AngularJS?

I've got a very basic page with a controller, I think it should be pretty obvious what I'm trying to do from the code, but it isn't working.

Here is my HTML

<!DOCTYPE html>
<html ng-app>

<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>

<body>
<h1>{{ 800 / 40 }} </h1>
<h1 ng-controller="MainController">{{message}}</h1>
</body>
</html>


With the following in script.js

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


The 800 / 40 is displaying 20, so that suggests the Angular script and ng-app is fine, but the value of message isn't being set. In the example the ng-controller is in a h1 tag, but I have also tried it in a div which wraps around the h1.

Any suggestions?

Thanks

Answer

You need to create an angular module

var myapp = angular.module('myApp', []);

myapp.controller('MainController', function($scope){
  $scope.message= "Hello";

})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<div ng-app="myApp">
    <h1 ng-controller="MainController">{{message}}</h1>
</div>

Comments