Thursday 25 February 2016

Angularjs Factory Service Example




HTML



<div class="container">
            <table width="100%">
                <tr>
                    <td align="left">
                        <div>
                           
                        </div>
                    </td>
                    <td align="right">
                        <div class="bar" width="100%">
                            <input type="text" ng-model="SerchText" class="form-control" placeholder="Enter SearchText" />
                        </div>
                    </td>
                </tr>
            </table>
            <table class="table table-hover" width="50%" id="mytable">
                <thead>
                    <tr>
                        <th>
                            Srno
                        </th>
                        <th>
                            EmployeeCode
                        </th>
                        <th>
                            Name
                        </th>
                        <th>
                            Last Name
                        </th>
                        <th>
                            State
                        </th>
                        <th>
                            City
                        </th>
                        <th>
                            Salary
                        </th>
                        <th>
                            Department
                        </th>
                        <th>
                            Edit/Delete
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="employee in employees|filter:SerchText">
                        <td>
                            {{$index+1}}
                        </td>
                        <td>{{employee.empcd}}</td>
                        <td>{{employee.fname}}</td>
                        <td>{{employee.lname}}</td>
                        <td>{{employee.state}}<span style="display:none">{{employee.state_id}}</span></td>
                        <td>{{employee.city}}<span style="display:none">{{employee.city_id}}</span></td>
                        <td>{{employee.salary|currency:"&#8377"}}</td>
                        <td>{{employee.Deptid|getdepartments}}</td>
                        <td>
                            <input type="button" value="Edit" class="btn btn-default" ng-click="Edit(employee.empcd)" data-toggle="modal" data-target="#myModal" />
                            <input type="button" value="Delete" class="btn btn-primary" ng-click="Delete(employee.empcd)" />
                        </td>
                    </tr>
                    <tr>
                        <td colspan="9" align="left">
                            <input type="button" value="Add Employee" class="btn btn-danger" ng-click="ShowSave()" data-toggle="modal" data-target="#myModal" />
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title" id="myModalLabel">Edit Employee</h4>
                    </div>
                    <div class="modal-body">
                        <table class="table table-hover">
                            <tr ng-show="showEmpcd">
                                <td>
                                    Enter EmployeeCode
                                </td>
                                <td>
                                    <input type="text" class="form-control" placeholder="Enter Employee Code" ng-model="newResult.empcd" />
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    Enter Name
                                </td>
                                <td>
                                    <input type="text" name="name" ng-model="newResult.fname" class="form-control" placeholder="Enter Name" required />
                                    <span ng-show="myform.name.$error.required&&myform.name.$dirty"></span>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    Last Name
                                </td>
                                <td>
                                    <input type="text" name="lname" ng-model="newResult.lname" class="form-control" placeholder="Enter Last Name" required />
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    State
                                </td>
                                <td>
                                    <!--<input type="text" name="state" ng-model="newResult.state" class="form-control" placeholder="Enter State" required />-->
                                    <select class="form-control" id="ddl_state" ng-model="newResult.state_id" ng-options="x.state_id as x.state_name for x in states" ng-change="GetCity(newResult.state_id)">
                                        <option value="">--Select State--</option>
                                    </select>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    City
                                </td>
                                <td>
                                    <select class="form-control" ng-model="newResult.city_id" ng-options="y.city_id as y.city_name for y in cities" ng-change="CheckCity(newResult.city_id)">
                                        <option value="">--Select City--</option>
                                    </select>
                                    <!--<input type="text" name="city" ng-model="newResult.city" class="form-control" placeholder="Enter City" required />-->
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    Salary
                                </td>
                                <td>
                                    <input type="text" name="salary" ng-model="newResult.salary" class="form-control" placeholder="Enter Salary ex:15000" disabled="disabled" />
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    Department
                                </td>
                                <td>
                                    <select data-ng-model="newResult.Deptid" data-ng-options="I.Deptid as I.deptname for I in Department" class="form-control">
                                        <option value="">--Select Department--</option>
                                    </select>
                                </td>
                            </tr>
                            <tr>
                                <td colspan="2">
                                    <button type="button" class="btn btn-primary" ng-disabled="myform.$invalid" ng-click="UpdateRecord()" data-dismiss="modal" ng-show="showUpdate">Update Record</button>
                                    <button type="button" class="btn btn-primary" ng-disabled="myform.$invalid" ng-click="SaveRecord()" data-dismiss="modal" ng-show="showSave">Save changes</button>
                                </td>
                            </tr>
                        </table>
                    </div>
                    <div class="modal-footer">
                    </div>
                </div>
            </div>
        </div>





Web Service
[WebMethod]
        public void GetEmployee()
        {
            List<Employee> emplist = new List<Employee>();
            string connection = ConfigurationManager.ConnectionStrings["myConnection"].ConnectionString;
            using (SqlConnection con = new SqlConnection(connection))
            {
                string query = "Usp_demo_crude";
                using (SqlCommand cmd = new SqlCommand(query, con))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@mode", "SELECT");
                    DataTable dt = new DataTable();
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    da.Fill(dt);
                    foreach (DataRow dr in dt.Rows)
                    {
                        Employee emp = new Employee();
                        emp.fname = dr["fname"].ToString();
                        emp.lname = dr["lname"].ToString();
                        emp.state = dr["state"].ToString();
                        emp.city = dr["city"].ToString();
                        emp.salary = Convert.ToInt32(dr["salary"]);
                        emp.Deptid = dr["Deptid"].ToString();
                        emp.empcd = dr["Empcode"].ToString();
                        emp.state_id = Convert.ToInt32(dr["state_id"]);
                        emp.city_id = Convert.ToInt32(dr["city_id"]);                      
                        emplist.Add(emp);
                    }
                    JavaScriptSerializer js = new JavaScriptSerializer();
                    Context.Response.Write(js.Serialize(emplist));
                }
            }
        }

        [WebMethod]
        public void SaveRecord(Employee objemp)
        {
            string connection = ConfigurationManager.ConnectionStrings["myConnection"].ConnectionString;
            using (SqlConnection con = new SqlConnection(connection))
            {
                string query = "Usp_demo_crude";
                SqlCommand cmd = new SqlCommand(query, con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@fname", objemp.fname);
                cmd.Parameters.AddWithValue("@empcode", objemp.empcd);
                cmd.Parameters.AddWithValue("@lname", objemp.lname);
                cmd.Parameters.AddWithValue("@stateid", objemp.state_id);
                cmd.Parameters.AddWithValue("@city_id", objemp.city_id);
                cmd.Parameters.AddWithValue("@salary", objemp.salary);
                cmd.Parameters.AddWithValue("@deptid", objemp.Deptid);
                cmd.Parameters.AddWithValue("@mode", "INSERT");
                con.Open();
                cmd.ExecuteNonQuery();
            }
        }

        [WebMethod]
        public void UpdateRecord(Employee objemp)
        {
            string connection = ConfigurationManager.ConnectionStrings["myConnection"].ConnectionString;
            using (SqlConnection con = new SqlConnection(connection))
            {
                string query = "Usp_demo_crude";
                SqlCommand cmd = new SqlCommand(query, con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@fname", objemp.fname);
                cmd.Parameters.AddWithValue("@empcode", objemp.empcd);
                cmd.Parameters.AddWithValue("@lname", objemp.lname);
                cmd.Parameters.AddWithValue("@state", objemp.state);
                cmd.Parameters.AddWithValue("@city", objemp.city);
                cmd.Parameters.AddWithValue("@salary", objemp.salary);
                cmd.Parameters.AddWithValue("@deptid", objemp.Deptid);
                cmd.Parameters.AddWithValue("@mode", "UPDATE");
                con.Open();
                cmd.ExecuteNonQuery();
            }
        }

        [WebMethod]
        public void DeleteRecord(string empcd)
        {
            string connection = ConfigurationManager.ConnectionStrings["myConnection"].ConnectionString;
            using (SqlConnection con = new SqlConnection(connection))
            {
                string query = "Usp_demo_crude";
                SqlCommand cmd = new SqlCommand(query, con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@mode", "DELETE");
                cmd.Parameters.AddWithValue("@empcode", empcd);
                con.Open();
                cmd.ExecuteNonQuery();
            }
        }

        [WebMethod]
        public void GetState()
        {
            List<GetState> objlst = new List<GetState>();
            string connection = ConfigurationManager.ConnectionStrings["myConnection"].ConnectionString;
            using (SqlConnection con = new SqlConnection(connection))
            {
                string query = "Usp_demo_crude";
                using (SqlCommand cmd = new SqlCommand(query, con))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@mode", "STATE");
                    DataTable dt = new DataTable();
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    da.Fill(dt);
                    foreach (DataRow dr in dt.Rows)
                    {
                        GetState objstate = new GetState();
                        objstate.state_id = dr["state_id"].ToString();
                        objstate.state_name = dr["state_name"].ToString();
                        objlst.Add(objstate);
                    }
                    JavaScriptSerializer js = new JavaScriptSerializer();
                    Context.Response.Write(js.Serialize(objlst));
                }
            }
        }

        [WebMethod]       
        public void GetCity(int state_id)
        {
            List<GetCity> objlst = new List<GetCity>();
            string connection = ConfigurationManager.ConnectionStrings["myConnection"].ConnectionString;
            using (SqlConnection con = new SqlConnection(connection))
            {
                string query = "Usp_demo_crude";
                using (SqlCommand cmd = new SqlCommand(query, con))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@mode", "CITY");
                    cmd.Parameters.AddWithValue("@stateid", state_id);
                    DataTable dt = new DataTable();
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    da.Fill(dt);
                    foreach (DataRow dr in dt.Rows)
                    {
                        GetCity objstate = new GetCity();
                        objstate.city_id = dr["city_id"].ToString();
                        objstate.city_name = dr["city_name"].ToString();
                        objlst.Add(objstate);
                    }
                    JavaScriptSerializer js = new JavaScriptSerializer();
                    Context.Response.Write(js.Serialize(objlst));
                }
            }
        }



Employee.cs

public class Employee
    {
        public string fname { get; set; }
        public string empcd { get; set; }
        public string lname { get; set; }
        public string state { get; set; }
        public string city { get; set; }
        public int salary { get; set; }
        public string Deptid { get; set; }
        public int state_id { get; set; }
        public int  city_id { get; set; }

    }




 
module.js
app.controller('myController', function ($log, $scope, myService) {
    var SuccessCallbackFunction = function (response) {
        $scope.employees = response.data;
    }

    var ErrorCallbackFunction = function (error) {
        $scope.employees = error.data;
    }

    $scope.getEmployees = function () {
        myService.GET_Employees().then(SuccessCallbackFunction, ErrorCallbackFunction);
    }

    $scope.showUpdate = false;
    $scope.showSave = false;
    $scope.showEmpcd = false;
    $scope.showEmpcd = true;

    $scope.Edit = function (id) {
        $scope.showEmpcd = false;
        $scope.showUpdate = true;
        $scope.showSave = false;
        for (i in $scope.employees) {
            if ($scope.employees[i].empcd == id) {
                $scope.newResult = angular.copy($scope.employees[i]);              
            }
        }
    }

    $scope.ShowSave = function () {
        $scope.disablesalary = true;
        $scope.showEmpcd = true;
        $scope.showUpdate = false;
        $scope.showSave = true;
        $scope.BindState();
        $scope.newResult = "";

        $scope.showUpdate = false;
        $scope.showSave = true;
    }

    $scope.UpdateRecord = function () {
        var empdetail = {};
        empdetail.empcd = $scope.newResult.empcd;
        empdetail.fname = $scope.newResult.fname;
        empdetail.lname = $scope.newResult.lname;
        empdetail.state = $scope.newResult.state;
        empdetail.city = $scope.newResult.city;
        empdetail.salary = $scope.newResult.salary;
        empdetail.Deptid = $scope.newResult.Deptid;
        myService.UpdateRecord(empdetail).then(function (result) {
            $scope.message = result.data;
            $scope.getEmployees();
        })
    }

    $scope.SaveRecord = function () {
        var empdetail = {};
        empdetail.empcd = $scope.newResult.empcd;
        empdetail.fname = $scope.newResult.fname;
        empdetail.lname = $scope.newResult.lname;
        //empdetail.state = $scope.newResult.state;
        //empdetail.city = $scope.newResult.city;
        empdetail.state_id = $scope.newResult.state_id;
        empdetail.city_id = $scope.newResult.city_id;
        empdetail.salary = $scope.newResult.salary;
        empdetail.Deptid = $scope.newResult.Deptid;
        myService.SaveEmployeeRecord(empdetail).then(function (result) {
            $scope.message = result.data;
            $scope.getEmployees();
        })
    }

    $scope.Delete = function (id) {
        if (confirm("Are you sure want to Delete Record with id " + id)) {
            myService.DeleteRecord(id).then(function (result) {
                $scope.message = result.data;
                $scope.getEmployees();
            })
        }
    }

    $scope.BindState = function () {
        myService.BindState().then(function (response) {
            $scope.states = response.data;
        })
    }

    $scope.GetCity = function (id) {
        if (id == null) {
            $scope.cities = "";
        }
        myService.GetCity(id).then(function (results) {
            $scope.cities = results.data;
        })
    }

    $scope.CheckCity = function (id) {      
        if (id == null) {
            $scope.newResult.state_id = "";
        }
    }

    $scope.Department = [
        { deptname: "IT", Deptid: "1" },
        { deptname: "Account", Deptid: "2" },
        { deptname: "Sales", Deptid: "3" },
        { deptname: "HR", Deptid: "4" },
        { deptname: "Admin", Deptid: "5" }
    ];

    //$scope.newResult.state_id = 1;

    $scope.BindState();

    $scope.getEmployees();
})




filter.js 

app.filter('getdepartments', function () {
    return function (input) {
        switch (input) {
            case "1":
                return "IT";
            case "2":
                return "Account";
            case "3":
                return "Sales";
            case "4":
                return "HR";
            case "5":
                return "Admin";
        }
    }
})



factory.js


app.factory('myfactory', function ($http) {
    var fact = {};

    fact.getEmployees = function () {
        return $http.get('WebService.asmx/GetEmployee');
    }

    fact.SaveEmployeeRecord = function (employee) {
        return $http({
            method: 'POST',
            url: 'WebService.asmx/SaveRecord',
            data: '{objemp:' + JSON.stringify(employee) + '}'
        });
    }

    fact.UpdateRecord = function (employee) {
        return $http({
            method: 'POST',
            url: 'WebService.asmx/UpdateRecord',
            data: '{objemp:' + JSON.stringify(employee) + '}'
        })
    }

    fact.DeleteRecord = function (id) {
        return $http({
            method: 'POST',
            url: 'WebService.asmx/DeleteRecord',
            data: '{empcd:' + id + '}'
        })
    }

    fact.BindState = function () {
        return $http.get('WebService.asmx/GetState')
    }

    fact.GetCity = function (id) {      
        var data = $.param({
            branch: id
        });

        var config = {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
            }
        }
        //return $http.post("WebService.asmx/GetCity", JSON.stringify({ 'state_id': id }), [config]).then(function (results) { alert(results.data); });
        return $http.post('WebService.asmx/GetCity', data, config)
    }

    return fact;
});


controller.js

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







No comments:

Post a Comment