Controllers in AngularJs

Controllers in AngularJs are where all the business logics are written. Lets first understand the term business logic first, then talking about controllers would just be a cake walk.

What is Business Logic:

Let us suppose, you are at a e-commerce site, and you are adding/deleting/updating the quantity of stuffs in your cart. For the user’s point of view you might have applied some coupon code’s to get deals, but on the backend there would have been a model of discounts where coupons were there and then validated. For the user now price has changed, but price is changed on the view for that particular user, all that interaction with data(model) and updating in the view(with two-way data binding) is all that comes in business logic is put in the view itself.

Controllers in template:

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

myApp.controller(‘HelloController’, [‘$scope’, function($scope) {
$scope
.wish = ‘Hi!’;

}]);

myApp declares the js code is AngularJs module. Which needs to be put on every controller that you would be using throughout in your program.

.controller constructor function is added to the myApp module so that our controller which is ‘HelloController’ is limited to the scope of this particular module.
$scope is injected here like dependency injections, the way services are, and here ‘wish’is our scope variable.
All this code is done in the js file which is our template here.

Controllers in View:

Controllers are then added to the dom using ng-controller. Now within the scope of the div, you can directly use any variables declared in controller js file, like here {{wish}} is being used for two way- data binding.

<div ng-controller="HelloController">


{{ wish }}

</div>

What’s new with AngularJs controllers:

Hence, as diagram clearly depicts, controllers hasn’t changed the game, it has just made the code now more organized than it was in the<script>, but the game changer here is two  way data binding which has tremendously enhanced coding experience!

Traditional Implementation                                                                                                                                                                                       

 

 

 

 

 

 

 

 

 

 

 

 

 

 

AngularJs Implementation

 

 

Hope, it would have made you clear with the  concept. If you still have an any doubt, leave it in the comment section below. Our team would revert back within 24 hours.

Do Follow our Facebook page https://www.facebook.com/lovebeingengineer/.

Similar Blogs:

Forms in AngularJs

 

Templates And Expressions in AngularJs

 

$scopes in AngularJs

Understanding Two-Way Data Binding in AngularJs

 

Journey of Angular

 

Services in AngularJs

$scopes in AngularJs

 

Dependency Injection in AngularJs!

 

Leave a Reply