Quantcast
Channel: TechieDreams
Viewing all articles
Browse latest Browse all 21

AngularJS Part 2 – Controllers and Two way binding

$
0
0

                  In the previous tutorial we learnt what AngularJS is and how Data binding works. So here in this tutorial we will move on to next important component ‘Controllers’.

Controllers:

As AngularJS follows MVC architecture we use Controllers to write all our business logic and also we can also update UI.

In the earlier example where we worked on data binding and how the model is associated with the element.
So now what if i need to write some business logic over the model, how to access the model from my JavaScript function?

Controllers answers these questions.

As simple, controller is nothing but a JavaScript function.

Actually there are 3 different types in writing a controller.

1. Normal JavaScript function:

So firstly before writing our function we need to mark the scope of our controller in the HTML using ‘ng-controller’ directive.

Here we marked the body tag with the controller so the ‘mainController’ will now have scope over all elements in the body.

<body ng-controller="mainController">

Now we declared our controller(mainController), so will define it as follows:

<script type="text/javascript">
        function mainController($scope) {
            $scope.name = "world";
        }
</script>

 $scope – Its a angular global variable where it holds the model objects defined inside the scope of controller.
Ex: we defined a model called name in HTML so no in side our controller function we can access it using $scope.
Also we can modify the model as shown in the example above.

Two way binding:

Also will discuss about two way biding here.
In the above example the model ‘name’ is initialized from controller as ‘world’, which will update the UI.
Other way when we input something in the ‘input field’ it will also update the UI.

So here from our mainController if we intend to access the updated model, its quite simple as angular will auto bind the model to
the input we can directly use it from the controller.

Here i modified the above example to demonstrate this:

<!DOCTYPE html>
<html ng-app="">
    <head>
        <title>AngularJS Bean Project</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width">
        <script src="js/libs/angular.js"></script>
        
    </head>
    <body ng-controller="mainController">
        <input type="text" ng-model="name"/>
        <br />
        Hello {{name}}!!
        <br />
        Hello <span ng-bind="name"></span>!!
        <br /><br />
        <button ng-click="showModel()">Alert update model!</button>
    </body>
    
    <script type="text/javascript">
        function mainController($scope) {
            $scope.name = "world";
            
            $scope.showModel = function() {
                alert($scope.name);
            };
        }      
    </script>
</html>

In the above HTML,  i added a button to alert the updated model.
In AngularJS we use ‘ng-click’ directive on elements to trigger a function when user clicks.
Here our callback function on click is ‘showModel’. We can access this though ‘$scope’ from our controller and implement as shown above.

We are just alerting the $scope.name, which will alert the updated value in the model. Thus we can modify a model from UI or from a controller.

Also the other two ways of writing a controller are:

2. Second is the module way. Where we need to first declare the module name in the HTML. In the above example we used ng-app directive to mark the angular code, the same directive accepts a value what will be our module.

So first we need to refer to our module via ‘angular.module’, it accepts two parameters first one the module name and next the dependencies
(A module can depend on another module or we can inject any angular components/Services which will use in the module).

So once you have the module we can create controller saying ‘module.controller’, which will accept two parameters first is the controller name second is the controller function. And in the function we can inject the dependencies as parameters.

angular.module('myApp', []).controller('mainController', function($scope) {
           $scope.name = "world";
        });

3. The third way is also the same as the 2nd but here what ever is injected in the controller function first will be declared as show below. So here the 2nd parameter

will be an array, where the last value will be the controller function.

Note: The parameter should be in the same order as they are declared in the array. Also this more safe way than others.

angular.module('myApp', []).controller('mainController', ['$scope', '$location', function($scope, $location) {
            $scope.name = "world";
        }]);

 

Download the code zip:

Live Demo:

In the upcoming tutorials will continue with the other components with example for each one.

NEXT: AngularJS Part 3 – Routing ($routeProvider, $location)

Subscribe, like and stay tuned!

 

The post AngularJS Part 2 – Controllers and Two way binding appeared first on Techie Dreams.


Viewing all articles
Browse latest Browse all 21

Trending Articles