What is a Controller
If you are familiar with the MVC architectural pattern then controllers are nothing new to you. But to for those that are not, the controller’s job is to receive input from the view and updates the model or get data from the model and and update the view. For further information about Model View Controllers click here.
By using the ng-controller directive on your html page (view) allows you to associate AngularJS controller to a view.
<div ng-controller="HelloWorldController"> </div>
Now you will need to create a controller in javascript called HelloWorldController. What this controller will be doing is assign “Hello, World!” to $scope.message so that the view can display.
The $scope object is the link between the controller and the view, its an execution context for expressions and it mimics the DOM structure of the application. The $scope object can watch expressions and send events.
var app = angular.module('app', []); app.controller('HelloWorldController', ['$scope', function($scope) { $scope.message = "Hello, World!"; }]);
Now back on your html page you are going to use databinding to display the message by wrapping the variable or model with two curly braces.
<div ng-controller="HelloWorldController"> {{message}} </div>
Functions in Controllers
In AngularJS controllers you can define functions that can be made available to your view. For example in the html page I have created a button called Click Me, when its clicked it executes the function called showMessage().
<div ng-controller="HelloWorldController"> <button ng-click="showMessage()">Click Me</button> <br/> {{message}} </div>
In the controller I have created a function called showMessage() and inside the body it sets the $scope.message with “Hello, World”.
app.controller('HelloWorldController', ['$scope', function($scope) { $scope.showMessage = function() { $scope.message = "Hello, World"; }; }]);
If you need to pass parameters you can do that too by adding parameters like this in the controller. Below I am defining the parameter called value for the function which will be concatenated with the string “Hello, ” and get assigned to the $scope.message.
$scope.showMessage = function(value) { $scope.message = "Hello, " + value; };
Next we will modify the html page by passing a string “World!!” to showMessage().
<div ng-controller="HelloWorldController"> <button ng-click="showMessage('World!!')">Click Me</button> <br/> {{message}} </div>
Click here to download the source code for this blog from GitHub. All the examples are available inside the LearnAngulerJS/Controllers folder.