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.