How to create custom filter in AngularJs


Custom_Filter

We can create our own custom filter depending on our own requirement. Here I will show one of the simple and interesting custom filters in below example

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="../Scripts/angular.js"></script>
    <script>
        var app = angular.module("MyApp", []);
        app.filter("reverse", function myfunction() {
            return function (input) {
                var result = "";
                 input = input || "";
                for (var i = 0; i < input.length; i++) {
                    result = input[i]+result;
                }
                return result;
            };
        });
    </script>
</head>
<body ng-app="MyApp">
    <div>
        <input type="text" name="name" ng-model="text" placeholder="Enter text" />
        <p>Input: {{text}}</p>
        <p>Filter Input :{{ text | reverse }}</p>
    </div>
</body>
</html>

Summary:
In this example we learnt to create the custom filter depending on our own requirement in angularJs.

How to implement pagination in AngularJs ?


Pagination

There are so many approaches to do pagination in angularJs. But using factory service approach is one of the easiest approaches to do pagination with Server side data.

Let see the step by step demo for this

Step1: Create one app.js file and write the code related with Consuming external service and Pagination related code as given below

var app = angular.module("MyApp", []);

//This service can be changed for real time data consumption. For simiplicity we have kept this code. 
app.factory("Item", function () {
    var items = [];
    for (var i = 1; i < 100; i++) {
        items.push({ id: i, name: "ProductName " + i, description: "Description " + i });
    }

    return {
        get: function (offset, limit) {
            return items.slice(offset, offset + limit);
        },
        total: function () {
            return items.length;
        }
    };
});

app.controller("PaginationCtrl", function ($scope, Item) {

    $scope.itemsPerPage = 5;
    $scope.currentPage = 0;

    $scope.range = function () {
        var rangeSize = 5;
        var ret = [];
        var start;

        start = $scope.currentPage;
        if (start > $scope.pageCount() - rangeSize) {
            start = $scope.pageCount() - rangeSize;
        }

        for (var i = start; i < start + rangeSize; i++) {
            ret.push(i);
        }
        return ret;
    };


    $scope.prevPage = function () {
        if ($scope.currentPage > 0) {
            $scope.currentPage--;
        }
    };

    $scope.prevPageDisabled = function () {
        return $scope.currentPage === 0 ? "disabled" : "";
    };

    $scope.nextPage = function () {
        if ($scope.currentPage < $scope.pageCount() - 1) {
            $scope.currentPage++;
        }
    };

    $scope.nextPageDisabled = function () {
        return $scope.currentPage === $scope.pageCount() - 1 ? "disabled" : "";
    };

    $scope.pageCount = function () {
        return Math.ceil($scope.total / $scope.itemsPerPage);
    };

    $scope.setPage = function (n) {
        if (n > 0 && n < $scope.pageCount()) {
            $scope.currentPage = n;
        }
    };

    $scope.$watch("currentPage", function (newValue, oldValue) {
        $scope.pagedItems = Item.get(newValue * $scope.itemsPerPage, $scope.itemsPerPage);
        $scope.total = Item.total();
    });

});

Step 2: Write the html code to render data and displaying pagination like given below

<!DOCTYPE html>
<html>
<head>
    <title></title>
	<meta charset="utf-8" />
    <script src="../Pagination/angular.js"></script>
    <script src="app.js"></script>
    <link href="../Style/bootstrap.css" rel="stylesheet" />

</head>
<body ng-app="MyApp">
    <div ng-controller="PaginationCtrl">
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>Id</th>
                    <th>ProductName</th>
                    <th>Description</th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="item in pagedItems">
                    <td>{{item.id}}</td>
                    <td>{{item.name}}</td>
                    <td>{{item.description}}</td>
                </tr>
            </tbody>
            <tfoot>
            <td colspan="3">
                <div class="pagination">
                    <ul>
                        <li ng-class="prevPageDisabled()">
                            <a href ng-click="prevPage()">« Prev</a>
                        </li>
                        <li ng-repeat="n in range()" ng-class="{active: n == currentPage}" ng-click="setPage(n)">
                            <a href="#">{{n+1}}</a>
                        </li>
                        <li ng-class="nextPageDisabled()">
                            <a href ng-click="nextPage()">Next »</a>
                        </li>
                    </ul>
                </div>
            </td>
            </tfoot>
        </table>
    </div>
</body>
</html>

Summary:

Here we saw that how to implement basic pagination functionality in AngularJs.

Validation with Bootstrap in AngularJs


Validation_With_Bootstrap

We can make very interactive UI validation with help of Bootstrap in AngularJs Framework. Here I will show one simple validation example with bootstrap in angularJs.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="../Scripts/angular.js"></script>
    <link href="../Style/bootstrap.css" rel="stylesheet" />
    <script>
        var app = angular.module("MyApp", []);
        app.controller("User", function ($scope) {
            $scope.error = function (name) {
                var s = $scope.form[name];
                return s.$invalid && s.$dirty ? "error" : "";
            };
        });
    </script>
</head>
<body ng-app="MyApp">
    <div ng-controller="User">
        <br />
        <form name="form" ng-submit="submit()" class="form-horizontal">
            <div class="control-group" ng-class="error('FirstName')">
                <label class="control-label" for="FirstName">FirstName</label>
                <div class="controls">
                    <input id="FirstName" name="FirstName" type="text"
                           ng-model="User.FirstName" placeholder="FirstName" required />
                    <span class="help-block" ng-show="form.FirstName.$invalid && form.FirstName.$dirty">
                      First Name is required.
                    </span>
                </div>

            </div>
            <div class="control-group" ng-class="error('LastName')">
                <label class="control-label" for="LastName">LastName</label>
                <div class="controls">
                    <input id="LastName" name="LastName" type="text"
                           ng-model="User.LastName" placeholder="LastName" required />
                    <span class="help-block" ng-show="form.LastName.$invalid && form.LastName.$dirty">
                        Last Name is required.
                    </span>
                </div>
            </div>
            <div class="control-group" ng-class="error('Address')">
                <label class="control-label" for="Address">Address</label>
                <div class="controls">
                    <input id="Address" name="Address" type="text"
                           ng-model="User.Address" placeholder="Address" required />
                    <span class="help-block" ng-show="form.Address.$invalid && form.Address.$dirty">
                        Address is required.
                    </span>
                </div>
            </div>
            
            <div class="control-group">
                <div class="controls">
                    <button ng-disabled="form.$invalid" class="btn">Submit</button>
                </div>
            </div>

            
        </form>
    </div>
</body>
</html>

Summary:

In this post we learnt that how to do validation with Bootstrap in angularJs

How to do validation in AngularJs


ValidationDemo

Validation is the one of important part of any library. In each library or Framework there will be different approach to do validation. Similarly there is some different way to do validation in AngularJs.

In AngularJs Form attribute play the main role in validation.

Now in below example we will see the demo example of doing validation of UserName and EmailId.

<!DOCTYPE html>
<html>
<head>
    <title></title>
	<meta charset="utf-8" />
    <script src="../Scripts/angular.min.js"></script>
    <script>
    var app = angular.module('myApp', []);
     app.controller('MyController', function($scope) {
     $scope.user = 'chandradev';
     $scope.email = 'chandradev@gmail.com';
});
    </script>
</head>

<body>
    <fieldset>
        <legend><b>Validation Example</b></legend>

        <form ng-app="myApp" ng-controller="MyController"
              name="myForm" novalidate>

            <p>
                UserName:<br>
                <input type="text" name="user" ng-model="user" required>
                <span style="color:red" ng-show="myForm.user.$dirty && myForm.user.$invalid">
                    <span ng-show="myForm.user.$error.required">UserName is required.</span>
                </span>
            </p>

            <p>
                Email:<br>
                <input type="email" name="email" ng-model="email" required>
                <span style="color:red" ng-show="myForm.email.$dirty && myForm.email.$invalid">
                    <span ng-show="myForm.email.$error.required">Email is required.</span>
                    <span ng-show="myForm.email.$error.email">Invalid Email ID.</span>
                </span>
            </p>

            <p>
                <input type="submit"
                       ng-disabled="myForm.user.$dirty && myForm.user.$invalid ||
                      myForm.email.$dirty && myForm.email.$invalid">
            </p>

        </form>
    </fieldset>
</body>

</html>

Point to remember:

1. In the above example ng-show=”myForm.user.$dirty && myForm.user.$invalid” is used to display the invalid message if the user type invalid data or left blank.

2. If the user will leave blank field then ng-show directive will display the error message as given below.

       <span ng-show="myForm.user.$error.required">UserName is required.</span>
       

3. For validation of emailid the given below code will do.

       <span ng-show="myForm.email.$error.email">Invalid Email ID.</span>
       

Summary:

In this article we learnt that how to do basic validation in angularJs

How to create User Control in AngularJs using Custom Directive ?


UserControl

We can create the user control in angular js like given below

Step 1: Create the basic HTML User control design like this

<!DOCTYPE html>
<html>
<head>
    <title></title>
	<meta charset="utf-8" />
    <!--<link href="../../Style/bootstrap.min.css" rel="stylesheet" />-->
</head>
<body>
    <div>
        <fieldset style="width:400px">
            <legend>
                Login Form
            </legend>

            UserName : <input type="text" name="txtUserName" value=" " /> <br /><br />
            Password : <input type="password" name="txtPaassword" /><br /><br />
            <button>Login</button>
        </fieldset>
    </div>
</body>
</html>

Step 2: Now create the custom angularJs directive i.e my-Widget and Call in Html form as given below

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="../../Scripts/angular.min.js"></script>

    <script>
        var app = angular.module("MyApp", []);
        app.directive("myWidget",function () {

            return {
                restrict: "E",
                templateUrl:"../Directive/MyLogin.html"
            };
        });
    </script>
</head>
<body ng-app="MyApp">
    <p>This is the first UserControl</p>
    <my-Widget></my-Widget>

    <p>This is the Second UserControl</p>
    <my-Widget></my-Widget>
</body>
</html>


Summary:
Here we saw that how to create the custom directive and use as reusable component in AngularJs.

Routing in AngularJs (Part 7)


In this article we will see how to implement the client side routing features in asp.net MVC application using angularJs.

It is one of the cool features of AngularJs Framework.
Now we will see how to implement it by step by step

Step1: Create the blank asp.net MVC 5 application using Visual Studio 2015/2013/2012.

EmptyProject

Step 2: Add the “HomeController“ in Controller folder.

AddController

Step3: Now generate the index view from the Home Controller. Write the code as given below

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div> 
    </div>
</body>
</html>

Step 4: Add the “RoutDemoController “ in RoutDemo folder and keep the following code to generate the partial view

PartialView

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Routing_Demo1.Controllers
{
    public class RoutDemoController : Controller
    {
        // GET: RoutesDemo
        public ActionResult One()
        {
            return PartialView();
        }

        public ActionResult Two()
        {
            return PartialView();
        }

        public ActionResult Three()
        {
            return PartialView();
        }
    }
}

Step 5: Generate the 3 separate partial views like this

<fieldset class="scheduler-border">
    <legend class="scheduler-border">Partial View Page1</legend>
    <p>This is the dummy Text. </p>
    <p>This is the dummy Text. </p><p>This is the dummy Text. </p><p>This is the dummy Text. </p><p>This is the dummy Text. </p>
</fieldset>

Step 6: Now keep the below code in index.cshtml file



<ul>
        <li><a href="/#/RouteOne">Route One</a></li>
        <li><a href="/#/RouteTwo">Route Two</a></li>
        <li><a href="/#/RouteThree">Route Three</a></li>
    </ul>

    <div ng-view></div>

Note:” ng-view” is the angular directive, which is used to render the partial view in given location.
Step 7: Download the angularJs and angular-route.js from Google and kept in Scripts folder.
Step 8: Add you own javascript file in MyScript Folder and write the code like this



var app = angular.module('AngularTest', ['ngRoute']);
var configFunction = function ($routeProvider) {
    $routeProvider
        .when('/RouteOne', {
            templateUrl: 'RoutDemo/One'
        })
        .when('/RouteTwo', {
            templateUrl: 'RoutDemo/Two'
        })
        .when('/RouteThree', {
            templateUrl: 'RoutDemo/Three'
        });
}
configFunction.$inject = ['$routeProvider'];

app.config(configFunction);

Step 9: Call all JavaScript library file in index page and donot forget to include “ng-view” angular directive to render the partial view. The complete code will be as given below.

IndexCodeChange

Step 10: Now run the application, you will see output like given below.

Routing_OP

Summary:
In this post you learn that how to use angularJs routing features in asp.net MVC application.

Consuming Web API Services in AngularJs (Part 6)


Angularjs framework has inbuilt support for consuming external service via $http.get method in json format. There are so many approaches to consume the service.

In this post I will explain one of the most popular approaches to consume external service using Ajax request from WEB API as external Service.

Step 1: Create the blank asp.net MVC 5.0 application.

Step 2: Go to controller folder and right click and add Web API EmpController like given below image

Web API ADD

Step3: Write the code in EmpController like this




using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebAPI_Sample.Models;
using System.Data;
using System.Data.SqlClient;

namespace WebAPI_Sample.Controllers
{
    public class EmpController : ApiController
    { 
      
       [HttpGet]
       public List<Emp> GetEmpDetails()
        {
            List<Emp> Emps = new List<Emp>();
            using (SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Database1.mdf;Integrated Security=True"))
            {
                con.Open();
                using (SqlCommand cmd = new SqlCommand("Select * from tblEmp", con))
                {
                    SqlDataReader dr = cmd.ExecuteReader();
                    while (dr.Read())
                    {
                        Emp objEmp = new Emp();
                        objEmp.Id = Convert.ToInt32(dr["Id"]);
                        objEmp.EmpName = dr["EmpName"].ToString();
                        objEmp.EmpAddress = dr["EmpAddress"].ToString();
                        objEmp.EmpSal = Convert.ToDecimal(dr["EmpSalary"]);
                        Emps.Add(objEmp);
                    }
                    return Emps;
                }
            }
        }

    }
}

Note: Make ensure that there is table I.e tblEmp in your database with Id, EmpName, EmpAddress, EmpSalary field and there should be some dummy data.

Step 4: Now build the application and make ensure that service is working as per as expected. For this you to click F5. Then you will get forbidden error message like this.

Forbidden_Error

Step 5: Now change the URL path like this to execute the Web Api Code

http://localhost:51808/api/Emp/GetEmpDetails

URL Change

Then you will get the data in xml format from Web api service like above image.

Step 6: Write the http get request to consume web api service in angularJs in plain HTML page like given below code




<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="../Scripts/angular.min.js"></script>
    <style>
        table, th, td {
            border: 1px solid grey;
            border-collapse: collapse;
            padding: 5px;
        }

            table tr:nth-child(odd) {
                background-color: #f1f1f1;
            }

            table tr:nth-child(even) {
                background-color: #ffffff;
            }
    </style>
    <meta charset="utf-8" />
</head>

<body>
    <fieldset>
        <legend>
            <b> Demo application to consume WEB API in AngualarJs</b>
        </legend>

            <div ng-app="myApp" ng-controller="EmpController">

                <table>
                    <thead>
                        <tr>
                            <th>Emp ID</th>
                            <th>EmpName</th>
                            <th>EmpAddress</th>
                            <th>EmpSal</th>
                        </tr>
                    </thead>
                    <tr ng-repeat="x in EmpNames">
                        <td>{{ x.Id }}</td>
                        <td>{{ x.EmpName }}</td>
                        <td>{{ x.EmpAddress }}</td>
                        <td>{{ x.EmpSal }}</td>
                    </tr>
                </table>

            </div>
       
    </fieldset>
    <script>
        //This is the Module in angular
        var app = angular.module('myApp', []);

        // This is the controller in angular
        app.controller('EmpController', function ($scope, $http) {
            $http.get("http://localhost:51808/api/Emp/GetEmpDetails")
           .success(function (response) {
               $scope.EmpNames = response;
           });

        });
    </script>

</body>

</html>

Step 7: Now run the HTML file and you will get out put like this

FinalOP

Summary:

In this article we learnt that how to create Wep API Service and how to consume it in AngularJs.