Skip to main content

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]);
                    });
                });
            }
        };
    }

]);


By Anil Singh | Rating of this article (*****)

Popular posts from this blog

Angular 2, 4, 5, 6, 7, 8 and 9 Interview Questions and Answers -Books

» Are you preparing for Angular Interview? Buy this book (Including Angular 8, 7, 6, 5,4, 2) Interview Q/A Interview Q/A Interview Q/A Interview Q/A Interview Q/A Interview Q/A Interview Q/A » A Complete Guide Book of Angular 9 This is a concise, complete overview of the key aspects of Angular 9. It is fully up to date with the latest release of Angular. This article provide all the important aspects required for angular developers looking for brief and useful content... Posted In Angular 9 » A Complete Guide Book of Angular 8 This is a concise, complete overview of the key aspects of Angular 9. It is fully up to date with the latest release of Angular. This article provide all the important aspects required for angular developers looking for brief and useful content... Posted In Angular 8 » A Complete Guide Book of Angular 7 This is a concise, complete overview of the key aspects of Angular 7. It is fully up to date with the latest release of Angular. This

39 Best Object Oriented JavaScript Interview Questions and Answers

Most Popular 37 Key Questions for JavaScript Interviews. What is Object in JavaScript? What is the Prototype object in JavaScript and how it is used? What is "this"? What is its value? Explain why "self" is needed instead of "this". What is a Closure and why are they so useful to us? Explain how to write class methods vs. instance methods. Can you explain the difference between == and ===? Can you explain the difference between call and apply? Explain why Asynchronous code is important in JavaScript? Can you please tell me a story about JavaScript performance problems? Tell me your JavaScript Naming Convention? How do you define a class and its constructor? What is Hoisted in JavaScript? What is function overloadin

25 Best Vue.js 2 Interview Questions and Answers

What Is Vue.js? The Vue.js is a progressive JavaScript framework and used to building the interactive user interfaces and also it’s focused on the view layer only (front end). The Vue.js is easy to integrate with other libraries and others existing projects. Vue.js is very popular for Single Page Applications developments. The Vue.js is lighter, smaller in size and so faster. It also supports the MVVM ( Model-View-ViewModel ) pattern. The Vue.js is supporting to multiple Components and libraries like - ü   Tables and data grids ü   Notifications ü   Loader ü   Calendar ü   Display time, date and age ü   Progress Bar ü   Tooltip ü   Overlay ü   Icons ü   Menu ü   Charts ü   Map ü   Pdf viewer ü   And so on The Vue.js was developed by “ Evan You ”, an Ex Google software engineer. The latest version is Vue.js 2. The Vue.js 2 is very similar to Angular because Evan You was inspired by Angular and the Vue.js 2 components looks like -

nullinjectorerror no provider for httpclient angular 17

In Angular 17 where the standalone true option is set by default, the app.config.ts file is generated in src/app/ and provideHttpClient(). We can be added to the list of providers in app.config.ts Step 1:   To provide HttpClient in a standalone app we could do this in the app.config.ts file, app.config.ts: import { ApplicationConfig } from '@angular/core'; import { provideRouter } from '@angular/router'; import { routes } from './app.routes'; import { provideClientHydration } from '@angular/platform-browser'; //This (provideHttpClient) will help us to resolve the issue  import {provideHttpClient} from '@angular/common/http'; export const appConfig: ApplicationConfig = {   providers: [ provideRouter(routes),  provideClientHydration(), provideHttpClient ()      ] }; The appConfig const is used in the main.ts file, see the code, main.ts : import { bootstrapApplication } from '@angular/platform-browser'; import { appConfig } from '

AngularJs input date format calendar

Table of Context bout  the input date.  Click for live demo on plnker 1. Allow to use of a custom date format like "yyyy/MM/dd" or "yyyy-MM-dd" etc. 2. Allow to check the input date typed by the user is correct or not. 1 2 3 4 //The model must be a Date object, otherwise Angular will throw an error. //The error is Invalid Date objects will be rendered as an empty string. i.e. The dates whose getTime() is NaN. //The model must be a Date object, otherwise Angular will throw an error. //The error is Invalid Date objects will be rendered as an empty string. i.e. The dates whose getTime() is NaN. The Example 1 code as given below. 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 <!doctype html> <html lang= "en" > <head>      <meta charset= "utf-8" />      <script src= " http://ajax.googleapis.com/ajax/lib