Saturday, May 7, 2016

ng-model in angular-js

Displaying data in the applications is a very basic need. To do so, angularcjs provides two main directives, apart from other directives. These are ng-model and ng-bindIn this article we will try to understand how ng-model can be used and why it is useful over ng-bind.

ng-Model and two way data binding:

ng-model supports two way data binding while ng-bind does not. Two way data binding means that when ng-model is used for any property/variable, and, when any change is made in it's value, it get's reflected, where-ever it is being used.

For example, suppose we have a property named "DefaultText", with any default value. This property is bind with an input control(to get input from user) and span tag(to display the value to the user), using the angular expression or ng-bind

When the page first loads, the input control will display the default value. The value flows from the variable in the controller to the input type control and also in the span tag with which it is being bind with. When value is changed in the input type control, it updates the underlined model property i.e. "DefaultText" and updated value is displayed in the span tag, as it is attached to it. 

Let's try this by creating a controller named ngModelBindController:

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

        mainApp.controller('ngModelBindController', function ($scope) {
            $scope.DefaultText = 'Enter a Value';
        });


Next, we bind the controller with a div in the html and use the ng-model directive to bind the DefaultText property to an input control of type text. Also we bind this property to the span tag using the angular expressions, to display the value of this variable. So our html will look like the following:


  <div ng-app="mainApp" ng-controller="ngModelBindController">
        <fieldset>
            <legend>ng-model in angular-js</legend>
            <p>
                Enter a value:
                <input type="text" ng-model="DefaultText" />
            </p>
            <span>You have entered: {{ DefaultText }}
            </span>
         </fieldset>
    </div>


Now run the application and we can see that the default value i.e. "Enter a Value" is displayed in the input control. Change the input control value and it will get's updated in the span tag.


ng-model in angular js



That's it, this is the basic working of ng-model. Hope you enjoyed reading it. Happy coding...!!!

1 comment: