AngularJS Controllers are most useful part of an AngularJS application. These are javascript functions/objects which perform majority of UI related work. They can be considered as the driver for Model and View changes. They are the gateway between the model (the data in our application), and the view (whatever a users sees on his screen and interacts with).
Their core responsibilities includes:
angular.module('myApp', []) .controller('AppController', [function() { var self= this; self.name = 'BLA BLA'; }]);
or if the module is defined elsewhere.
var App = angular.module('myApp',['ui.bootstrap', 'ngResource']);//in some file App.controller('AppController', [function() { var self= this; self.name = 'BLA BLA'; }]);
angular.module
function to create a module if it does not existcontroller
function on the module.var App = angular.module('myApp',['ui.bootstrap', 'ngResource']);//in some file App.controller('AppController', ['$log', '$location', function($log, $location) { var self= this; self.name = 'BLA BLA'; self.sayHello = function(){alert('say hello');} $log.log('I am starting'); $location.path("/newpath") }]);
In above example, our controller depends on few built-in AngularJS services [$log
service used to simply log strings to console, $location
service used to interact with the URL in the browser bar]. First we need to add the dependencies as strings in the array (this is known as ‘safe style of Dependency Injection’). Then we will inject them as variables (you can give it any name) into the function that is passed as the last argument in the array.
AngularJS will pick up the individual strings in the array, look up the services internally, and inject them into the function in the order in which we have defined the strings. Once the services are injected, we can use them within our controller. In this case, the controller definition function simply logs a string to the console, and set the URL to /newpath.
Using ng-controller
directive.
<body ng-controller="AppController as ctrl"> <label>Name :</label><input type="text" ng-model="ctrl.name" placeholder="Enter your name"/><br/><br/> <span ng-bind="ctrl.name"></span><br/><br/> <button ng-click="ctrl.sayHello()"> Hello </button> ..... </body>
In order to use a Controller in UI, we make use of another popular AngularJS directive : ng-controller
. This directive is primarily used to associate an instance of a controller with a UI element. In this particular example, we applied it on body.
With ng-controller, we have provided a name to this particular instance of AppController, called ctrl using as keyword. This is known as the controllerAs syntax in AngularJS [Bla as b]. Using controllerAs syntax, we can give each instance of the controller a name in order to recognize its usage in the HTML. Note that we can even have different instances of same controller used in different places in UI, in that case controllerAs will be handy to relate which instance is controlling which part of HTML.
Anyone coming from AngualrJS background will be wondering where all those $scope stuff have gone. With the new controllerAs syntax, you can simply avoid using $scope unless in specific situations. The controllerAs syntax gives a clear impression when looking in HTML about who is doing what in UI.
Just for comparison, let’s rewrite above snippet using $scope this time:
var App = angular.module('myApp',['ui.bootstrap', 'ngResource']);//in some file App.controller('AppController', ['$scope','$log', '$location', function($scope, $log, $location) { $scope.name = 'BLA BLA'; $scope.sayHello = function(){alert('say hello');} $log.log('I am starting'); $location.path("/newpath") }]);
This time, instead of using this
, we are creating a property and a function directly on $scope which we have added as a dependency, and will be injected by AngularJS. Now let’s see what our view will look like:
<body ng-controller="AppController"> <label>Name :</label><input type="text" ng-model="name" placeholder="Enter your name"/><br/><br/> <span ng-bind="name"></span><br/><br/> <button ng-click="sayHello()"> Hello </button> ..... </body>
In above snippet, we have removed the controllerAs syntax, just controller name. As a result we are directly using the property and function by their names. This may seem nice here, but imagine when you have a complicated UI involving different components, it will make it hard for anyone reading the code to understand which property or function belongs to which component. This is one of reason to prefer controllerAs syntax over $scope counterpart.
One of the best explanation available on AngualrJS scope can be found at This link, which will answer all your scope related questions. In this section, however, i will just put few words from 30000 feet view.
Look at this example.
<html ng-app="myApp"> <head> <title>Controller Demo</title> </head> <body ng-controller="AppController as ctrl"> <label>Name :</label><input type="text" ng-model="ctrl.name" placeholder="Enter your name"/><br/><br/> <span ng-bind="ctrl.message"></span> <span ng-bind="ctrl.name"></span><br/><br/> <button ng-click="ctrl.changeMessage()"> Change Message </button> <button ng-click="ctrl.resetMessage()"> Reset Message </button> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"> </script> <script> angular.module('myApp', []) .controller('AppController', [function() { var self = this; self.name=''; self.message= 'Hello'; self.changeMessage = function() { self.message = 'Bye'; }; self.resetMessage = function() { self.message = 'Hello'; }; }]); </script> </body> </html>
Let’s dig deeper into details.
ng-controller
. This directive is primarily used to associate an instance of a controller with a UI element. In this particular example, we applied it on body.ng-model
directive to store the value that the user types into this field into Controller’s ‘name’ variable.ng-bind
.ng-click
. The ng-click directive evaluates any expression passed to it when the button is clicked. In this case, we ask AngularJS to trigger the controller’s changeMessage()/resetMessage() functions when clicked.When you type something in text box, the view is updated immediately to reflect it, thanks to AngularJS data-binding. Additionally, on startup, Application shows ‘Hello’ message but on clicking the changeMessage button (which simply sets the message variable in controller to a different value), the text in UI changes to ‘Bye’. It is interesting because we did not have to tell the UI to update. It happened automatically.
In a complex design, We can well face a need of nested controllers. AngularJS controllerAs again help us there to identify the individual instances/parent instances.
Look at below example.
<html ng-app="myApp"> <head> <title>Nested Controller Demo</title> <style> body{font-family:"Arial";background-color:#E2E2DC} div { margin:10px;padding:10px; border:2px solid red; } </style> </head> <body> <div ng-controller="FirstController as first"> type : {{ first.type }} <div ng-controller="SecondController as second"> type: {{ second.type }} Parent type: {{ first.type }} <div ng-controller="ThirdController as third"> type: {{ third.type }} Parent type: {{ second.type }} Parent parent type: {{ first.type }} </div> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"> </script> <script> angular.module('myApp', []) .controller('FirstController', [function() { var self = this; self.type='FirstController'; }]) .controller('SecondController', [function() { var self = this; self.type='SecondController'; }]) .controller('ThirdController', [function() { var self = this; self.type='ThirdController'; }]); </script> </body> </html>
An AngularJS controller is directly linked to a view or HTML. If your controller contains some logic which is not used in UI, then it should not be there in controller at first place, and you should move that logic to Services.
If you like tutorials on this site, why not take a step further and connect me on Facebook , Google Plus & Twitter as well? I would love to hear your thoughts on these articles, it will help improve further our learning process.
In this post we will be developing a full-blown CRUD application using Spring Boot, AngularJS, Spring Data, JPA/Hibernate and MySQL,…
Spring Boot complements Spring REST support by providing default dependencies/converters out of the box. Writing RESTful services in Spring Boot…
Being able to start the application as standalone jar is great, but sometimes it might not be possible to run…
Spring framework has taken the software development industry by storm. Dependency Injection, rock solid MVC framework, Transaction management, messaging support,…
Let's secure our Spring REST API using OAuth2 this time, a simple guide showing what is required to secure a…
This post shows how an AngularJS application can consume a REST API which is secured with Basic authentication using Spring…
View Comments