Controllers allow functions to be registered with AngularJS and follow its MVC architecture. Controllers are JavaScript objects that handle data flow between models and views by calling functions to get data from models to display in views. They also initialize scope objects and handle business logic. To use a controller, a module must first be created and the controller registered with it by specifying the controller name and function. The view then associates to the controller using ng-controller.
2. Why Controllers?
Use of Global functions is not recommended in Angularjs.
Angularjs follows MVC Architecture so it expects the function to be registered with it before using the function.
Writing or initializing the variable within the HTML tags is not recommended because it has to follow the MVC
standards.
We have to use all the angular features.
EX:<div ng-app="" ng-init="myText=20">//NOT RECOMMENDED
3. What are Controllers?
Controllers can be defined as the code which will call different functions to get the right data from model
to view.
A Controller is a JavaScript Object created by JavaScript Constructor.It can be mainly used to initialization
means to set the initial state of your $scope object.
It can also be defined as binding data to the View and also handling the data flow into your angular
application.
All the business logics are handled with the controllers in the Angularjs.
4. How to Use Controller?
A Controller has to be always registered with the module.
The ng-controller defines the application controller.
Before creating a controller we have to create a module and register the controller with it.
Creating a Module
Var modules=angular.module(“myModule”[ ] );
It takes two parameters first one is module name and second one is the array for dependent modules.
5. How to Use Controller?
Creating Controller:
modules.controller(“myController”,Main);
Here the two parameters are “myController” is the Controller name and Main is the Method name.
Example:
https://codepen.io/nikhil12/pen/qjEewJ