AngularJs Controllers

AngularJS Controllers

We saw, how Angular helps in creating models and views and we also noticed that there is a bi-directional communication between view and model in Angular.

Let us now see what is the role of Angular controller and how an Angular controller can be created and used.

Controller:

  • Controller is the most important building block or the central player of AngularJS. It is structurally a JavaScript object containing some properties and functions.
  • Logics like creation of model, initialization of model, creation of functions for manipulation of model, persistence or retrieval of model data from server, etc can be housed by the Angular controller.
  • It controls the flow of data in the application.
  • It constructs the model and publishes it to the view, along with some callback methods with the help of a special object called, $scope.
  • $scope is a simple JavaScript Object that glues the model between the view and the controller.

Let us look into how Controllers can be declared in AngularJS.

Ways to create Angular Controller Syntax Visibility Key Points
1. Declare as global function function Ctrl($scope){ //controller logic } - It is simple JavaScript function containing $scope as an argument
Not supported in recent versions (1.4 onwards)
2. Declaring controller on entire app, i.e., the main module of the application Var app = angular.module("app",[]); app.controller(‘Ctrl’, function($scope){ //Controller logic }); <html ng-app="app"> The main module is loaded automatically when the application bootstraps using ng-app directive.
The visibility of the controller is to the module app
3. Declaring controller in a module within the main module var app=angular.module("app", [‘controllers’]); var controllers=angular.module("controllers",[]); controllers.controller(‘Ctrl’, function($scope){ //controller logic }); <html ng-app="app"> The main module is loaded automatically when the application bootstraps using ng-app directive
The visibility of the controller is to the module ‘controllers’ and visibility of module controllers is to the module ‘app’
#AngularJS_Controllers #Angular_Controllers #Ways_to_create_Angular_Controller #angular_scope #dropdown_in_angularjs

(New page will open, for Comment)

Not yet commented...