AngularJS tutorial:
- AngularJs hello world example
- AngularJs controller examples
- AngularJs ng-repeat example
- AngularJs Built-in filter example
- AngularJs custom filter example
- AngularJs ajax example using $http
- AngularJS RESTful web service JAXRS CRUD example using $http
What are controllers
What is $scope?
How controllers and scope are related?

Declaration of controller syntax :
1 2 3 4 5 6 7 |
var app = angular.module('myApp', []); app.controller('java2blogContoller', function($scope) { $scope.java2blogMsg = "Hello from java2blog"; }); |
Simple example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Angular js</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script> <script src="app.js"></script> </head> <body> <div ng-app="myApp" ng-controller="java2blogContoller"> </br> {{java2blogMsg}} !!! </div> </body> </html> |
app.js
1 2 3 4 5 6 7 |
var app = angular.module('myApp', []); app.controller('java2blogContoller', function($scope) { $scope.java2blogMsg = "Hello from java2blog"; }); |
Live Demo:
What if you don’t want to use $scope?
- Code becomes more readable.
- It removes dealing with this scope and bindings.
- There is no dependency on alias used in view(.html) and javascript
Lets take an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Angular js</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script> <script src="app.js"></script> </head> <body> <div ng-app="myApp" ng-controller="java2blogContoller as con"> </br> {{con.java2blogMsg}} !!! </div> </body> </html> |
app.js
1 2 3 4 5 6 7 8 |
var app = angular.module('myApp', []); app.controller('java2blogContoller', function() { var cont= this; cont.java2blogMsg = "Hello from java2blog with controller as option"; }); |