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"> <head> <title>Learn AngularJS - Functions</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.14/angular.min.js"></script> <script src="app.js"></script> </head> <body ng-controller="AppController"> <input type="button" ng-click="onClick()" value="Click Here" /> <div><h1>{{message}}</h1></div> </body> </html>