Showing posts with label Angular js. Show all posts
Showing posts with label Angular js. Show all posts

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-bind. In 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...!!!

Saturday, April 30, 2016

CRUD Operations using AngularJS

Recently I started exploring the angular js. So i decided to try with basic crud operations and create a new application. So let's see how we can do this. For our purpose, we will be using javascript arrays rather then any database. So let's start by adding 
Remove the web.config file and add an html page. To use angular js, we will add reference to online angular js script file on the following link.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js">

To start with our sample, we will add data into a javascript array. For this, add two input type controls and and buttons to save data. Also, add a new angular module and define a model named EmpModel in it, having three properties called Id, Name and Salary. Bind this model with our input controls, by our angular module named mainApp and a controller named CRUDController. So our code will look like the following:

<!DOCTYPE html>  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head>  
    <title></title>  
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>  
</head>  
<body>  
  
    <div ng-app="mainApp" data-ng-controller="CRUDController">  
  
        <table>  
            <tr>  
                <td>EmpId: </td>  
                <td>  
                    <span>{{ EmpModel.Id }}</span></td>  
            </tr>  
            <tr>  
                <td>Name:</td>  
                <td>  
                    <input type="text" data-ng-model="EmpModel.Name" /></td>  
            </tr>  
            <tr>  
                <td>Salary:</td>  
                <td>  
                    <input type="number" data-ng-model="EmpModel.Salary" /></td>  
            </tr>  
            <tr>  
                <td></td>  
                <td>  
                    <input type="button" value="Save Data"/></td>  
            </tr>  
        </table>  
    </div>  
  
    <script type="text/javascript">  
        var app = angular.module("mainApp", []);  
  
        app.controller('CRUDController', function ($scope) {  
            $scope.EmpModel = {  
                Id: 0,  
                Salary: 0,  
                Name: '',  
            };   
        });  
    </script>  
</body>  
</html> 

To add data into our javascript array, let's add a method named AddData. This method will receive the data from $scope and add it to the array. So our controller will change to: 

var app = angular.module("mainApp", []);  
       app.controller('CRUDController', function ($scope) {  
  
           $scope.EmpModel = {  
               Id: 0,  
               Salary: 0,  
               Name: '',  
           };  
  
           $scope.EmpList = [];  
           $scope.AddData = function () {  
               var _emp = {  
                   Id: $scope.EmpList.length + 1,  
                   Name: $scope.EmpModel.Name,  
                   Salary: $scope.EmpModel.Salary  
               };  
               $scope.EmpList.push(_emp);  
               ClearModel();  
           }  
  
           function ClearModel() {  
               $scope.EmpModel.Id = 0;  
               $scope.EmpModel.Name = '';  
               $scope.EmpModel.Salary = 0;  
           }  
       });  

Bind the AddData method to our button using ng-click angular directive. To display the data, we use the ng-repeat directive which will read the data from the array and generate an html table. So our html form will look like the following:

 <table>  
           <thead>  
               <th>Id</th>  
               <th>Name</th>  
               <th>Salary</th>  
           </thead>  
           <tr data-ng-repeat="Emp in EmpList">  
               <td>{{ Emp.Id }}</td>  
               <td>{{ Emp.Name }}</td>  
               <td>{{ Emp.Salary }}</td>  
           </tr>  
       </table>  

Now, run the application and see the data get's added.


Now let's delete the record from the table. Add a function for deletion in the controller. So our controller code will change to the following:

$scope.DeleteData = function (emp) {  
               var _index = $scope.EmpList.indexOf(emp);  
               $scope.EmpList.splice(_index, 1);  
           }  

The argument of this function is of type EmpModel and will contain the data of the record which we are going to delete. We will find index of the record and remove it from the array. Next bind the delete button click event with our delete function using ng-click and pass the EmpModel instance as the parameter. See the code below: 

 <table border="1" style="width: 300px">  
          <thead>  
              <th>Id</th>  
              <th>Name</th>  
              <th>Salary</th>  
          </thead>  
          <tr data-ng-repeat="Emp in EmpList">  
              <td>{{ Emp.Id }}</td>  
              <td>{{ Emp.Name }}</td>  
              <td>{{ Emp.Salary }}</td>  
              <td>  
                  <input type="button" value="Delete" data-ng-click="DeleteData(Emp)" /></td>  
          </tr>  
      </table>  

Run the code, add new records and try to delete them.


Now, let's perform the update. First will display the data to be updated, in our input controls. Add a new method named BindSelectedData in our controller, which will pass the data to the input controls, using the $scope.EmpModel. Our function will look like the following:


$scope.BindSelectedData = function (emp) {  
    $scope.EmpModel.Id = emp.Id;  
    $scope.EmpModel.Name = emp.Name;  
    $scope.EmpModel.Salary = emp.Salary;  
}  

To use the above method, bind it to the table row click using ng-click directive. Our html will change to:  

<table border="1" style="width: 300px">  
          <thead>  
              <th>Id</th>  
              <th>Name</th>  
              <th>Salary</th>  
          </thead>  
          <tr data-ng-repeat="Emp in EmpList" data-ng-click="BindSelectedData(Emp)">  
              <td>{{ Emp.Id }}</td>  
              <td>{{ Emp.Name }}</td>  
              <td>{{ Emp.Salary }}</td>  
              <td>  
                  <input type="button" value="Delete" data-ng-click="DeleteData(Emp)" /></td>  
          </tr>  
      </table>  

Select rows from the table and see that the data get's bind to the input controls through the $scope.EmpModel, which get;s the data from the emp object(argument of the BindSelectedData method). See the screenshot below:

Finally we will add the update button to perform the data updation. Add a method called UpdateData in the controller. So our controller will change to the following:

$scope.UpdateData = function () {  
    $.grep($scope.EmpList, function (e) {  
        if (e.Id == $scope.EmpModel.Id) {  
            e.Name = $scope.EmpModel.Name;  
            e.Salary = $scope.EmpModel.Salary;  
        }  
    });  
    ClearModel();  
}  

Our method will find the record in our array and perform it's updation. Attach our method with the click event of our update button by using the ng-click directive. So html mark-up will change to: 

<table>  
          <tr>  
              <td>EmpId: </td>  
              <td>  
                  <span>{{ EmpModel.Id }}</span></td>  
          </tr>  
          <tr>  
              <td>Name:</td>  
              <td>  
                  <input type="text" data-ng-model="EmpModel.Name" /></td>  
          </tr>  
          <tr>  
              <td>Salary:</td>  
              <td>  
                  <input type="number" data-ng-model="EmpModel.Salary" /></td>  
          </tr>  
          <tr>  
              <td>  
                  <input type="button" value="Save Data" data-ng-click="AddData()" /></td>  
              <td>  
                  <input type="button" value="Update Data" data-ng-click="UpdateData()" /></td>  
          </tr>  
      </table>  

Run the application, edit and record and click the Update button..

That's it, our basic application is ready to use. Hope you enjoyed reading this article. Happy coding...!!!

Friday, April 29, 2016

ng-repeat in Angularjs

It is quite common to display records in grid format in applications. In this article, we will discuss how we can do this in angular js.

Angular js uses the concept of directives(which extends the html attributes), to bind data to records which can be displayed in html controls. In this discussion, we will see how we can use the ng-repeat directive in angular js to display data in grid format.

To start with, we will create a angular controller and add some data in an array. So our code will look like the following:


var app = angular.module("myApp", []);  
        app.controller('ngRepeatExampleController', function ($scope, $http) {  
  
            $scope.Users = [];  
  
            $scope.Users.push({ UserId: 1, UserName: 'User X' });  
            $scope.Users.push({ UserId: 2, UserName: 'User Y' });  
            $scope.Users.push({ UserId: 3, UserName: 'User Z' });  
  
        });  

Next step is to bind the controller we created, with a parent div in html. For this we use ng-controller directive. To bind the data in the table format from the array, we will apply the ng-repeater element at the table row level. It will be simply how we use the foreach loop in C#. The difference is that we do not have an intellisense help here. So our code will look like the following:


 <div ng-app="myApp" data-ng-controller="ngRepeatExampleController">  
       <table border="1" style="width: 200px">  
           <thead>  
               <th>User Id</th>  
               <th>User Name</th>   
           </thead>  
           <tr data-ng-repeat="User in Users">  
               <td>{{ User.UserId }}</td>  
               <td>{{ User.UserName }}</td>   
           </tr>  
       </table>   
   </div>  

Run the application and we can see the data getting displayed in grid format.


Hope you enjoyed reading it. Happy coding...!!!

Saturday, April 9, 2016

Simple example to illustrate the controllers in Angular-js

Controllers are one of the very elegant way to communicate/pass data to the view. Simply create functions and properties in javascript, write the business logic and use the angular js directives and we are done. For this purpose, it uses $scope, which basically acts as a carrier of data between the controller and the view.

So let's create a sample calculator application, to illustrate how we can use the controllers in angular js. For this, add a javascript file and declare a controller with the following syntax:


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

mainApp.controller('calculatorController', function ($scope) {
 
    }
});

Here, the mainApp is the application level angular module and in this module we add or register a controller named calculatorController. The controller function accepts two parameters, where first one is the name of the controller and second represents the controller itself, with functions and properties we will use.

Within this controller, we will create the required properties and functions we need. We add two properties named firstNumber and secondNumber and a function to perform their sum using function named calculateSum. This is done through the use of $scope variable.So the controller will look like:


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

mainApp.controller('calculatorController', function ($scope) {

    $scope.firstNumber = 1;
    $scope.secondNumber = 2;

    $scope.calculateSum = function () {
        return $scope.firstNumber + $scope.secondNumber;
    }
});

Next, we simply need to bind this controller to the view. For this, we add an html page and add the reference to the external angular js using external reference. Also add reference to the external controller js file we created.


https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js 

Further, we add a div and two textboxes inside it. We bind the controller to the div using the ng-controller directive, using following syntax:


<div ng-app="mainApp" ng-controller="calculatorController">
</div>

We bind the model properties i.e. firstNumber and secondNumber using the ng-model directive. So our textboxes will look like the following:


<input type="text" ng-model="firstNumber">
<input type="text" ng-model="secondNumber">

We display the sum of these two numbers in a span, by binding the calculateSum using the angular expressions syntax. Since the angular js support two way data-binding, through ng-model, when we change the values in the textboxes, the updated values get reflected in the span tag. So the span tag will look like the following:


   <span>{{ calculateSum() }}</span>

So our complete html form will look like:





Run the application and change the values and see the results.

Hope you enjoyed reading it. Happy coding...!!!

Friday, March 25, 2016

two way data binding in angular.js using ng-model

In angular js, we have two directives ng-model and ng-bind. For a novice like me, both of them may sound same until they are explored in depth. However, they are not. The big difference between the two is that ng-model supports two way binding and ng-bind does not.

To understand the two-way binding, suppose we have an input type control. We need to display the value entered in the control in any span or div tag, as the value is getting changed i control. Then we normally use jQuery or some event like 'key-up', to display the value, as it get's changed. However, in angular js, we can easily do this using the ng-model directive. 

Let's create a small example to understand this. First we create an input type control and bind it with a model property named "sampleValue", using the ng-model directive. 




<input type="text" ng-model="sampleValue">


Next, we will use the angular expressions to display the value in the span tag. So our code will look like:

You have entered: <span ng-bind="sampleValue"></span>

That's it, we are done. Run the application enter any value in the input type and see the value changes in the span tag also. See the image below:


So the complete code will look like the below:

!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
</head>
<body>
    <div ng-app="">
        <fieldset>
            <legend>ng-Model Example</legend>
            <h4>Display the model data changed in the SPAN tag, using ng-Model</h4>
            <p>
                Enter a value:
            <input type="text" ng-model="sampleValue">
            </p>
            <p>You have entered: <span ng-bind="sampleValue"></span></p>
        </fieldset>
        <br />
    </div>
</body>
</html>

Hope you liked reading it....Happy coding...!!!