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

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 '

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 -

55 Best TypeScript Interview Questions and Answers - JavaScript!

What Is TypeScript? By definition, "TypeScript is a typed superset of JavaScript that compiles to plain JavaScript." TypeScript is a superset of JavaScript which provides optional static typing, classes and interfaces. => The TypeScript was first made public in the year 2012. => Typescript is a modern age JavaScript development language. => TypeScript is a strongly typed, object oriented, compiled language. => TypeScript was designed by Anders Hejlsberg (designer of C#) at Microsoft. => TypeScript is both a language and a set of tools. As an Example of TypeScript, class Hello {     msg : string ;      constructor ( message : string ) {          this . msg = message ;      }       getMsg () {          return "Hello, " + this . msg ;      } } TypeScript introduced a great deal of syntax taken from object-oriented programming, including but not limited to: 1) Interfaces 2) Classes 3) Enumerated t

.NET Core MVC Interview Questions and Answers

» OOPs Interview Questions Object Oriented Programming (OOP) is a technique to think a real-world in terms of objects. This is essentially a design philosophy that uses a different set of programming languages such as C#... Posted In .NET » .Net Constructor Interview Questions A class constructor is a special member function of a class that is executed whenever we create new objects of that class. When a class or struct is created, its constructor is called. A constructor has exactly the same name as that of class and it does not have any return type… Posted In .NET » .NET Delegates Interview Questions Delegates are used to define callback methods and implement event handling, and they are declared using the "delegate" keyword. A delegate in C# is similar to function pointers of C++, but C# delegates are type safe… Posted In .NET » ASP.Net C# Interview Questions C# was developed by Microsoft and is used in essentially all of their products. It is mainly used for