In the previous blog I have explained about the basics of AngularJS. I hope the reader has a basic understanding of AngularJS by now. If not please read my first article on Angular to have a basic understanding.
Let’s move one step ahead and let’s talk about “Controllers” in AngularJS.
Controllers
Controller controls the data of application.Ok look at it this way, let's say I have a class and I have a few properties in that. Now how can I access the same?? The answer is, I need to create an object of by class to get the properties. Sounds logical!!!
Like the same AngularJS controller is a JavaScript object containing attributes/properties and functions. Each controller accepts $scope as a parameter and through this only we can access the details.
Code Example:
I have used the same example as given in the first article of AngularJS.
- <body data-ng-app="testController" >
-
- <div data-ng-controller="myController">
- <p>Input Values to concatinate:</p>
- <p>Var1: <input type="text" data-ng-model="Var1"></p>
- <p>Var2: <input type="text" data-ng-model="Var2"></p>
-
-
- {{Var1}} + {{Var2}} = {{Var1 + Var2}}
-
- </div>
-
- <div> One way</div>
- <script>
- var obj = angular.module('testController', []);
- obj.controller('myController', function ($scope) {
- $scope.Var1 = "Nishant";
- $scope.Var2 = "Mittal";
- });
-
- </script>
Code Explanation
Step 1: I have defined AngularJS in body Tag,
- <body data-ng-app="testController" >
Step 2: I used “ng-controller” tag to define the Controller.
- <div data-ng-controller="myController">
Step 3: I have defined the input fields.
Step 4: Now the tricky one. In the script I have defined,
- var objAnotherway = angular.module('testController', []);
angular.module use to create , register and access the Angular modules. All the modules defined in the application should be registered in the same way.
Usage
- angular.module(name, [requires], [configFn]);
Arguments
Param |
Type |
Details |
name |
string |
The name of the module to create or retrieve. |
requires
(optional) |
!Array.<string>= |
If specified then new module is being created. If unspecified then the module is being retrieved for further configuration. |
configFn
(optional) |
Function= |
Optional configuration function for the module. Same as Module#config(). |
Step 5 - Now finally
- obj.controller('myController', function ($scope) {
- $scope.Var1 = "Nishant";
- $scope.Var2 = "Mittal";
What is $Scope
When ever any function or model we apply on view or html page it becomes only accessible using $Scope.
In the above example you are defining attributes named Var1 and Var2 with its value. The best part is the value will automatically pick up from controller and display it on screen.
Stay tuned for more on AngularJS and Others as well.