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

Wednesday, 16 November 2016

Setting route and embed partial views in Angular JS

Let's see with an example:

Table Used


select * from EmployeeTest


Step 1: This is going to be the structure.Include angular.js or angular.min.js file.




Step 2: In web.config file

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <webServices>
      <protocols>
        <add name="HttpGet"/>
      </protocols>
    </webServices>
  </system.web>
  <connectionStrings>
    <add name="EmplyoeeDB" connectionString="data Source=.;database=employee; integrated security=SSPI" providerName="Sql.Data.SqlClient"/>
  </connectionStrings>
</configuration>

Step 3: Lets create 4 partial html files which are going to be embed in Index.html

1. In Filter.html

<input type="text" ng-model="searchText.firstName" placeholder="Search By firstName" />
<input type="text" ng-model="searchText.lastName" placeholder="Search By lastName" />
<input type="text" ng-model="searchText.Gender" placeholder="Search By Gender" />
<input type="text" ng-model="searchText.DateOfBirth" placeholder="Search By DateOfBirth" /><br /><br />
<input type="checkbox" ng-model="completeMatch" />Match Complete Text
<input type="checkbox" ng-model="hideSalary" />Hide Salary
<input type="checkbox" ng-model="hideExperiance" />Hide Experiance
<input type="checkbox" ng-model="maskDOB" />Mask Date Of Birth
<br /><br />
<table>
    <thead>
        <tr>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Gender</th>
            <th ng-hide="maskDOB">Date Of Birth</th>
            <th ng-show="maskDOB">Date Of Birth</th>
            <th ng-hide="hideSalary">Salary</th>
            <th ng-show="!hideExperiance">Experiance > 3</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="employee in employees | filter:searchText:completeMatch">
            <td>{{employee.firstName}}</td>
            <td>{{employee.lastName}}</td>
            <td>{{employee.Gender}}</td>
            <td ng-hide="maskDOB">{{employee.DateOfBirth}}</td>
            <td ng-show="maskDOB">######</td>
            <td ng-hide="hideSalary">{{employee.Salary}}</td>
            <td ng-show="!hideExperiance">{{employee.Experiance | experiance}}</td>
        </tr>
    </tbody>
</table>

2. In FilterandSort.html

    Number of Rows : <input type="number" min="0" max="50" step="1" ng-model="numberofRows" />
<br /><br />
<table>
    <thead>
        <tr>
            <th ng-click="sortInfo('firstName')">First Name<div ng-class="sortInfoClass('firstName')"></div></th>
            <th ng-click="sortInfo('lastName')">Last Name<div ng-class="sortInfoClass('lastName')"></div></th>
            <th ng-click="sortInfo('Gender')">Gender<div ng-class="sortInfoClass('Gender')"></div></th>
            <th ng-click="sortInfo('DateOfBirth')">Date Of Birth<div ng-class="sortInfoClass('DateOfBirth')"></div></th>
            <th ng-click="sortInfo('Salary')">Salary<div ng-class="sortInfoClass('Salary')"></div></th>
            <th>Increment Salary By 1000</th>
            <th>Decrement Salary By 1000</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="employee in employees | limitTo:numberofRows |orderBy:sortColumn:reverseSort">
            <td>{{employee.firstName}}</td>
            <td>{{employee.lastName}}</td>
            <td>{{employee.Gender}}</td>
            <td>{{employee.DateOfBirth}}</td>
            <td>{{employee.Salary}}</td>
            <td><input type="button" value="Increment" ng-click="incrementSalary(employee)" /></td>
            <td><input type="button" value="Decrement" ng-click="decrementSalary(employee)" /></td>
        </tr>
    </tbody>
</table>


3. In CallingWebServiceFromJS.html


<table border="1">
    <thead>
        <tr>
            <th>EmpID</th>
            <th>EmpName</th>
            <th>EmpDesignation</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="employee in employees">
            <td>{{employee.EmpID}}</td>
            <td>{{employee.EmpName}}</td>
            <td>{{employee.EmpDesignation}}</td>
        </tr>
    </tbody>
</table>


 4. In UsingCustomService.html

<table border="1">
    <tr>
        <td>Enter Text :</td>
        <td><input type="text" ng-model="InputText" /></td>
    </tr>
    <tr>
        <td>Text in UpperCase :</td>
        <td><input type="text" ng-model="OutputUpper" /></td>
    </tr>
    <tr>
        <td>Text in LowerCase :</td>
        <td><input type="text" ng-model="OutputLower" /></td>
    </tr>
    <tr>
        <td>Text Length :</td>
        <td><input type="text" ng-model="OutputLength" /></td>
    </tr>
    <tr>
        <td></td>
        <td><input type="button" value="Manipulate String" ng-click="ManipulateString(InputText)" /></td>
    </tr>
</table>

Step 4 : In Employee.cs

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

namespace AngularRouting
{
    public class Employee
    {
        public int EmpID { get; set; }
        public string EmpName { get; set; }
        public string EmpDesignation { get; set; }

    }
}

Step 5 : In EmployeeService.asmx

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Services;

namespace AngularRouting.WebServices
{
    /// <summary>
    /// Summary description for EmployeeService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    // [System.Web.Script.Services.ScriptService]
    public class EmployeeService : System.Web.Services.WebService
    {
        [WebMethod]
        public void GetEmployeeData()
        {
            List<Employee> employeeObj = new List<Employee>();
            String CS = ConfigurationManager.ConnectionStrings["EmplyoeeDB"].ConnectionString;
            using (SqlConnection sqlcon = new SqlConnection(CS))
            {
                SqlCommand sqlcmd = new SqlCommand("Select * from EmployeeTest", sqlcon);
                sqlcon.Open();
                SqlDataReader sqlReader = sqlcmd.ExecuteReader();
                while (sqlReader.Read())
                {
                    Employee employee = new Employee();
                    employee.EmpID = Convert.ToInt32(sqlReader["EmpID"]);
                    employee.EmpName = sqlReader["EmpName"].ToString();
                    employee.EmpDesignation = sqlReader["EmpDesignation"].ToString();
                    employeeObj.Add(employee);
                }
            }
            JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
            Context.Response.Write(javaScriptSerializer.Serialize(employeeObj));
        }
    }
}

Step 5 : In StyleSheet.css

.header {
    text-align: center;
}

.leftMenu {
    height: 400px;
    width: 150px;
}

.mainContent {
    height: 400px;
    width: 700px;
}

a {
    display: block;
    padding: 5px;
}

Step 6: In Index.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" ng-app="RoutingExample">
<head>
    <title></title>
    <script src="../Scripts/External/angular.js"></script>
    <script src="../Scripts/External/angular-route.min.js"></script>
    <link href="../Resources/StyleSheet.css" rel="stylesheet" />
    <script src="../Scripts/App/Module.js"></script>
</head>
<body>
    <table border="1">
        <tr>
            <td colspan="2" class="header">
                <b>Angular Route Example</b>
            </td>
        </tr>
        <tr>
            <td class="leftMenu">
                <a href="#/Filter">Filter</a>
                <a href="#/FilterandSort">FilterandSort</a>
                <a href="#/CallingWebServiceFromJS">Calling WebService From JS</a>
                <a href="#/UsingCustomService">Using CustomService</a>
            </td>
            <td colspan="4" class="mainContent">
                <ng-view></ng-view>
            </td>
        </tr>
    </table>
</body>
</html>

Step 7: In Module.js

/// <reference path="../External/angular.js" />
/// <reference path="../Services/StringManipulationService.js" />

var myapp = angular.module("RoutingExample", ["ngRoute"])
.config(function ($routeProvider) {
    $routeProvider
    .when("/Filter", {
        templateUrl: "Filter.html",
        controller: "FilterController"
    })
    .when("/FilterandSort", {
        templateUrl: "FilterandSort.html",
        controller: "FilterandSortingController"
    })
    .when("/CallingWebServiceFromJS", {
        templateUrl: "CallingWebServiceFromJS.html",
        controller: "CallingWebServiceFronJSController"
    })
    .when("/UsingCustomService", {
        templateUrl: "UsingCustomService.html",
        controller: "UsingCustomServiceController"
    })
    .otherwise({
        redirectTo : "/Filter"
    })
})

.controller("CallingWebServiceFronJSController", function ($scope, $http) {
    $http.get('../../WebServices/EmployeeService.asmx/GetEmployeeData')
    .then(function (response) {
        $scope.employees = response.data;
    });
})
.service("StringManipulationService", function () {
    return {
        ManipulatedString: function (input) {
            if (!input) {
                return input;
            }

            var OutputUpper = "";
            var OutputLower = "";
            var OutputLength = 0;

            OutputUpper = input.toUpperCase();
            OutputLower = input.toLowerCase();
            OutputLength = input.length;
            return OutputUpper + "," + OutputLower + "," + OutputLength;
        }
    }
})
.controller("UsingCustomServiceController", function ($scope, StringManipulationService) {
    $scope.ManipulateString = function (input) {

        var strOutput = StringManipulationService.ManipulatedString(input);//Calling Custom Service Method
        $scope.OutputUpper = strOutput.split(',')[0];
        $scope.OutputLower = strOutput.split(',')[1];
        $scope.OutputLength = strOutput.split(',')[2];
    }
})
.controller("FilterandSortingController", function ($scope) {
    var employees = [
        { firstName: "Sanjeet", lastName: "Singh", Gender: "Male", DateOfBirth: "23/07/1991", Salary: 31000 },
        { firstName: "Sarah", lastName: "Singhania", Gender: "Female", DateOfBirth: "11/04/1990", Salary: 35000 },
        { firstName: "Tanuj", lastName: "Joshi", Gender: "Male", DateOfBirth: "06/12/1992", Salary: 22000 },
        { firstName: "Aaina", lastName: "Tyagi", Gender: "Female", DateOfBirth: "07/07/1993", Salary: 26000 },
    ];
    $scope.employees = employees;
    $scope.numberofRows = 4;
    $scope.sortColumn = "firstName";
    $scope.reverseSort = false;
    $scope.sortInfo = function (column) {
        $scope.reverseSort = ($scope.sortColumn == column) ? !$scope.reverseSort : false;
        $scope.sortColumn = column;
    }
    $scope.sortInfoClass = function (column) {
        if ($scope.sortColumn == column) {
            return $scope.reverseSort ? 'reverseSort' : 'Sort'
        }
        return '';
    }

    $scope.incrementSalary = function (employee) {
        employee.Salary = employee.Salary + 1000;
    }
    $scope.decrementSalary = function (employee) {
        employee.Salary = employee.Salary - 1000;
    }
})
.filter("experiance", function () {
    return function (experiance) {
        if (experiance > 3) {
            return "Yes";
        }
        else {
            return "No";
        }
    }
})
.controller("FilterController", function ($scope) {
        var employees = [
            { firstName: "Sanjeet", lastName: "Singh", Gender: "Male", DateOfBirth: "23/07/1991", Salary: 31000, Experiance: 2 },
            { firstName: "Sarah", lastName: "Singhania", Gender: "Female", DateOfBirth: "11/04/1990", Salary: 35000, Experiance: 4 },
            { firstName: "Tanuj", lastName: "Joshi", Gender: "Male", DateOfBirth: "06/12/1992", Salary: 22000, Experiance: 5 },
            { firstName: "Aaina", lastName: "Tyagi", Gender: "Female", DateOfBirth: "07/07/1993", Salary: 26000, Experiance: 1 },
        ];
        $scope.employees = employees;
});

Step 8: Let's run the application






 Put any random name after #/ it will be redirected to Filter page