AngularJS: Controller Functions

To create a controller function that can be use with an element’s event attribute, you need to define a function with it’s implementation in it and then attached it to the $scope.

Below I have created a new Javascript file called app.js with a controller called AppController. In the $scope I have a property for storing text and one for attaching a function called onClick. When the onClick function is invoked, the message property will be set with a message ‘Hello, World!’:

var app = angular.module('app.demo', []);

// Controllers
app.controller('AppController', ['$scope', function($scope) {
		$scope.message = '';
		$scope.onClick = function() {
			$scope.message = 'Hello, World!';

Below I create a html page with body that uses the AppController controller, I have a input element that is a button type and I use ng-click to bind the function that I have create in the controller. I have created a div that will display the message property every time the button is clicked:

<html ng-app="app.demo">
	<title>Learn AngularJS - Functions</title>
	<script src=""></script>
	<script src="app.js"></script>
	<body ng-controller="AppController">
		<input type="button" ng-click="onClick()" value="Click Here" />

Download Source Code

AngularJS: Controllers

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">