angularjs ng grid crud operations example code

AngularJs ng-grid CRUD Operations Example Code

//This is current loged user UIds.
var uid = parseInt(session().UID);

var app = angular.module('companyApp', ['ngGrid']);
app.service('getCompanyService', function ($http) {
    this.getCompanies = function () {
        return $http({
            method: 'GET',
            url: baseURL + 'Api/CompanyPref/Get/' + uid
        });
    };

    this.updateCompany = function (comp) {
        return $http.post(baseURL + "Api/CompanyPref/UpdateCompany/" + uid, comp)
           .success(function (data, status, headers, config) {
               $('#idUpdtMsg').show();
           });
    };

    this.uploadBulkComapnyFileToUrl = function (file) {
        var fdata = new FormData();
        var url = baseURL + "Home/fileUpload/" + uid + "_Inbox";
        fdata.append('file', file);

        return $http.post(url, fdata, {
            transformRequest: angular.identity,
            headers: { 'Content-Type': undefined }
        });
    };
});

app.controller('getCompanyServiceCtrl', function ($scope, getCompanyService) {
    $scope.companies = null;
    $scope.UID = null;
    $scope.AlertOptIn = false;
    $scope.EmailOptIn = false;

    $scope.C50Percent = false;
    $scope.C60Percent = false;
    $scope.C70Percent = false;
    $scope.C80Percent = false;
    $scope.C85Percent = false;
    $scope.C90Percent = false;
    $scope.C95Percent = false;
    $scope.C100Percent = false;
    $scope.C105Percent = false;
    $scope.C110Percent = false;
    $scope.C115Percent = false;
    $scope.C120Percent = false;
    $scope.C125Percent = false;

    $scope.loading = true;
    $scope.uploadCompany = false;
    $scope.upValidCompany = false;

    //This is used to get the company detils on grid.
    getCompanyService.getCompanies().then(function (resp) {
        if (resp.data !== undefined) {
            $scope.companies = resp.data;
            $scope.UID = resp.data[0].UID;
        }       
    })
    .finally(function () {
        // called no matter success or failure
        $scope.loading = false;
    });

    var editRowTemplate = '<span style="display:block; text-align:center;"><button ng-click="editRowIndex(col, row)" class="btn btn-xs btn-default" data-toggle="modal" data-target="#companyUpdateModal"><i class="fa fa-pencil"></i></button>&nbsp;</span>';
    var multiplePercntFieldsInSingleCell = '<div class="row"><div class="col-md-2" ng-if="row.entity.C50Percent == true">50% </div> <div class="col-md-2" ng-if="row.entity.C60Percent == true">60%</div><div class="col-md-2" ng-if="row.entity.C70Percent == true">70%</div><div class="col-md-2" ng-if="row.entity.C80Percent == true">80%</div><div class="col-md-2" ng-if="row.entity.C85Percent == true">85%</div></div><div class="row"><div class="col-md-2" ng-if="row.entity.C90Percent == true">90%</div><div class="col-md-2" ng-if="row.entity.C95Percent == true">95%</div><div class="col-md-2" ng-if="row.entity.C100Percent == true">100%</div><div class="col-md-2" ng-if="row.entity.C105Percent == true">105%</div><div class="col-md-2" ng-if="row.entity.C110Percent == true">110%</div></div><div class="row"><div class="col-md-2" ng-if="row.entity.C115Percent == true">115%</div><div class="col-md-2" ng-if="row.entity.C120Percent == true">120%</div><div class="col-md-2" ng-if="row.entity.C125Percent == true">125%</div></div>';
    var multipleLastUpdateFieldsInSingleCell = '<div>{{row.entity.LastUpdateBy}},  {{row.entity.LastUpdateDate | date:"yyyy-MM-dd"}}</div>';
    var multipleAlertFieldsInSingleCell = '<div>AlertOptIn : <strong ng-if="row.entity.AlertOptIn">Yes!</strong><strong ng-if="!(row.entity.AlertOptIn)">No!</strong> <br /> EmailOptIn : <strong ng-if="row.entity.EmailOptIn">Yes!</strong><strong ng-if="!(row.entity.EmailOptIn)">No!</strong></div>';


    $scope.companyColumns = [
            {
                field: 'AlertOptIn', displayName: 'Alert Options', width: "15%",
                cellTemplate: multipleAlertFieldsInSingleCell
            },
            {
                field: 'C50Percent', displayName: 'Alerts Percent', width: "60%",
                cellTemplate: multiplePercntFieldsInSingleCell
            },
            {
                field: 'LastUpdateBy', displayName: 'LastUpdateBy', width: "18%",
                cellTemplate: multipleLastUpdateFieldsInSingleCell
            },
            {
                field: 'remove', displayName: '', width: "7%",
                cellTemplate: editRowTemplate
            }];

    $scope.filterOptions = {
        filterText: ''
    };

    $scope.setPagingData = function (data, page, pageSize) {
        if (page == null) {
            page = 1;
        }
        var pagedData = data.slice((page - 1) * pageSize, page * pageSize);
        $scope.companies = pagedData;
        $scope.pagingOptions.totalServerItems = data.length;
        if (!$scope.$$phase) {
            $scope.$apply();
        }
    };

    $scope.getPagedDataAsync = function (pageSize, page) {
        setTimeout(function () {
            getCompanyService.getCompanies().then(function (resp) {
                if (resp.data !== undefined) {                   
                    $scope.setPagingData(resp.data, page, pageSize);
                }
            });
        }, 100);
    };

    $scope.$watch('pagingOptions', function () {
        $scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage);
    }, true);

    $scope.pagingOptions = {
        pageSizes: [10, 20, 50, 100],
        pageSize: 10,
        totalServerItems: 0,
        currentPage: 1
    };

    $scope.companyGridView = {
        data: 'companies',
        rowHeight: 70,
        columnDefs: 'companyColumns',
        plugins: [new pluginNgGridCVSExport()],
        enablePaging: true,
        showFooter: true,
        enableCellSelection: true,
        enableRowSelection: true,
        filterOptions: $scope.filterOptions,
        pagingOptions: $scope.pagingOptions
    };

    $scope.removeRowIndex = function (col, row) {
        var index = this.row.rowIndex;
        $scope.companyGridView.selectItem(index, false);
        $scope.companies.splice(index, 1);

        if (row.entity !== undefined && row.entity !== null) {
            //deleteUserFromServer(row.entity);
        }
    };

    $scope.editRowIndex = function (col, row) {
        var index = this.row.rowIndex;
        if (row.entity !== undefined && row.entity !== null) {
            setEditRowPopups(row.entity);
            //This is used to hide the msg if row is updated.
            $('#idUpdtMsg').hide();
        }
    };

    function setEditRowPopups(row) {
        $scope.AlertOptIn = row.AlertOptIn;
        $scope.EmailOptIn = row.EmailOptIn;

        $scope.C50Percent = row.C50Percent;
        $scope.C60Percent = row.C60Percent;
        $scope.C70Percent = row.C70Percent;
        $scope.C80Percent = row.C80Percent;
        $scope.C85Percent = row.C85Percent;
        $scope.C90Percent = row.C90Percent;
        $scope.C95Percent = row.C95Percent;
        $scope.C100Percent = row.C100Percent;
        $scope.C105Percent = row.C105Percent;
        $scope.C110Percent = row.C110Percent;
        $scope.C115Percent = row.C115Percent;
        $scope.C120Percent = row.C120Percent;
        $scope.C125Percent = row.C125Percent;
    }

    $scope.uploadFile = function () {
        var file = $scope.myFile;
        if (file !== undefined && file.name.length > 0) {
            var type = (file.name).split('.');
            if (type[1] !== undefined) {
                if (type[1] == 'xlsx' || type[1] == 'xls') {
                  getCompanyService.uploadBulkComapnyFileToUrl(file).then(function (resp) {
                        if (resp !== undefined) {
                            $scope.uploadCompany = true;
                            $scope.upValidCompany = false;
                            $('#filAccount').val('');

                            //This is used to get the company detils on grid.
                            getCompanyService.getCompanies().then(function (resp) {
                                if (resp.data !== undefined) {
                                    $scope.companies = resp.data;
                                    $scope.UID = resp.data[0].UID;
                                }
                            })
                        }
                    });
                }
                else {
                    $scope.uploadCompany = false;
                    $scope.upValidCompany = true;
                    $('#filAccount').val('');                   
                }
            }
        }
    };

    //This is used to Reset mobiles upload file.
    $scope.restUploadMsg = function () {
        $scope.uploadCompany = false;
        $scope.upValidCompany = false;
    };

    //download excel file fron server.
    $scope.downloadFile = function () {
        var urlBase = OBPCX.ALERT.baseURL;
        if (urlBase !== undefined && urlBase.length > 0) {
            window.location.href = urlBase + "Download/Sample/Company.xlsx";
        }
    };

    //Update company Events.
    $scope.updateCompany = function () {
        var compInput = {
            UID: $scope.UID,
            AlertOptIn: $scope.AlertOptIn,
            EmailOptIn: $scope.EmailOptIn,

            C50Percent: $scope.C50Percent,
            C60Percent: $scope.C60Percent,
            C70Percent: $scope.C70Percent,
            C80Percent: $scope.C80Percent,
            C85Percent: $scope.C85Percent,
            C90Percent: $scope.C90Percent,
            C95Percent: $scope.C95Percent,
            C100Percent: $scope.C100Percent,
            C105Percent: $scope.C105Percent,
            C110Percent: $scope.C110Percent,
            C115Percent: $scope.C115Percent,
            C120Percent: $scope.C120Percent,
            C125Percent: $scope.C125Percent
        };

        //This is company services used to call update company APIs.
        getCompanyService.updateCompany(compInput).then(function () {
            getCompanyService.getCompanies().then(function (resp) {
                $scope.companies = resp.data;
            });
        });

        //This is used to show the msg if row is updated.
        $('#idUpdtMsg').show();
    };
});

app.directive('ngConfirmBoxClick', [
      function () {
          return {
              link: function (scope, element, attr) {
                  var msg = attr.ngConfirmBoxClick || "Are you sure?";
                  var clickAction = attr.confirmedClick;
                  element.bind('click', function (event) {
                      if (window.confirm(msg)) {
                          scope.$eval(clickAction)
                      }
                  });
              }
          };
      }
]);

app.directive('fileModel', ['$parse',
    function ($parse) {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                var model = $parse(attrs.fileModel);
                var modelSetter = model.assign;
                element.bind('change', function () {
                    scope.$apply(function () {
                        modelSetter(scope, element[0].files[0]);
                    });
                });
            }
        };
    }

]);


ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..
My Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.