Add buttons or links to Angular UI Grid rows to implement click events + multi-select deletion instances

function init() {

//Picture Preview

self.BtnViewImg = BtnViewImg;

}

ng-click=”grid.appScope.BtnViewImg(row)”

(function () {
    'use strict';
    angular.module('Nancanl.PR.ProductAPP.DeliveryFile').config(ListScreenRouteConfig);

    ListScreenController.$inject = ['Nancanl.PR.ProductAPP.DeliveryFile.DeliveryFile.service', '$state', '$stateParams', '$rootScope', '$scope', 'common.base', 'common.services.logger.service', 'common.widgets.notificationTile.globalService',
        'commonService', 'common.widgets.busyIndicator.service', 'common.services.authentication', '$translate'
    ];

    function ListScreenController(dataService, $state, $stateParams, $rootScope, $scope, base, loggerService, notificationService, commonService, busyIndicatorService, auth, $translate) {
        var self = this;
        var logger, rootstate, messageservice, backendService;

        activate();

        //Initialization function
        function activate() {
            logger = loggerService.getModuleLogger('Nancanl.PR.ProductAPP.DeliveryFile.DeliveryFile');


            init();
            //Get logged in user information
            GetUserInfo();
            initGridOptions();
            initGridData();
        }

        function init() {
            logger.logDebug('Initializing controller....');

            rootstate = 'home.Nancanl_PR_ProductAPP_DeliveryFile_DeliveryFile';
            messageservice = base.widgets.messageOverlay.service;
            backendService = base.services.runtime.backendService;

            //Initialize Model Data
            self.searchParams = {};
            self.selectedItem = null;
            self.selectedItems = null;
            self.isButtonVisible = false;
            self.viewerOptions = {};
            self.viewerData = [];

            self.Machineid = angular.copy($stateParams.Id);
            if (self.Machineid == null) {

                $state.go('home.Nancanl_PR_ProductAPP_DeliveryMachineInfo_DeliveryMachineInfo');
                return;
            }
            //Expose Model Methods
            self.addButtonHandler = addButtonHandler;
            self.editButtonHandler = editButtonHandler;
            self.cameraButtonHandler = cameraButtonHandler;
            //self.selectButtonHandler = selectButtonHandler;
            self.deleteButtonHandler = deleteButtonHandler;
            //Picture Preview
            self.BtnViewImg = BtnViewImg;
        }

        //Get logged in user information
        function GetUserInfo() {
            var user = auth.getUser();
            self.UserId = user['nameid'];
            self.UserCode = user['unique_name'];
            self.UserName = user['urn:fullname'];
            console.log("user---------------------", JSON.stringify(user));
        }

        //Initialize grid options
        function initGridOptions() {
            self.gridOptions = {
                fastWatch: true,
                rowHeight: 35,
                minimumColumnSize: 100,
                enableMultiSelection: false,
                enableFiltering: false,
                //Basic properties
                enableSorting: true, //Whether sorting (column) is supported
                useExternalSorting: false, //Whether custom sorting rules are supported
                enableGridMenu: false, //Whether to display the table menu
                showGridFooter: true, //Display the footer of the table
                enableHorizontalScrollbar: 1, //Horizontal scroll bar of the table
                enableVerticalScrollbar: 1, //Vertical scroll bar of the table (both 1-display, 0-not display)
                selectionRowHeaderWidth: 30,
                enableCellEditOnFocus: false, //default is false, when true, click to open editing (when cellEdit is true, you need to introduce 'ui.grid.cellNav')
                //pagination properties
                enablePagination: true, //Whether to paginate, default is true
                enablePaginationControls: true, //Use default bottom pagination
                paginationPageSizes: [20, 30, 50, 70, 90, 100], //Number of options displayed per page
                paginationPageSize: 20, //Number of items displayed on each page
                paginationCurrentPage: 1, //Current page number
                totalItems: 0, // total quantity
                useExternalPagination: true, //Whether to use paging buttons
                //Select
                rowTemplate: " <div ng-dblclick ="grid.appScope.onDblClick(row)" ng-repeat="(colRenderIndex, col) in colContainer.renderedColumns track by col.colDef.name " class="ui-grid-cell" ng-class="{ 'ui-grid-row-header-cell': col.isRowHeader }" ui-grid-cell></div>", //Double-click row event
                enableFooterTotalSelected: true, // Whether to display the total number of selected items, the default is true, if displayed, showGridFooter must be true
                enableFullRowSelection: true, //Whether to click anywhere in the row to select it. The default is false. When it is true, the checkbox can be displayed but cannot be selected.
                enableRowHeaderSelection: true, //Whether to display the selected checkbox, default is true
                enableRowSelection: true, // Whether row selection is available, default is true;
                enableSelectAll: true, //Select whether all checkboxes are available, default is true;
                enableSelectionBatchEvent: true, //default is true
                modifierKeysToMultiSelect: false, //default is false. When it is true, you can only press the ctrl or shift key to perform multiple selections. At this time, multiSelect must be true;
                multiSelect: true, // Whether multiple selections can be made, the default is true;
                noUnselect: false, //default is false, whether it can be unselected after selection
                appScopeProvider: self,
                columnDefs: [{
                        name: 'rowNum',
                        displayName: 'serial number',
                        width: 60,
                        enableSorting: false,
                        cellTemplate: '<div class="ui-grid-cell-contents">{<!-- -->{grid.renderContainers.body.visibleRowCache.indexOf(row) + 1}}</div>\ '
                    },
                    {
                        field: 'FileName',
                        displayName: 'File name',
                        width: 210,
                        cellTemplate: '<div class="ui-grid-cell-contents"><a title="Preview photo" href="javascript:void(0);" style="color:# 006487" ng-click="grid.appScope.BtnViewImg(row)">{<!-- -->{row.entity.FileName}}</a></div>'
                    },
                    {
                        field: 'CreatedUserName',
                        displayName: 'Creator',
                        width: 250
                    },
                    {
                        field: 'CreatedOn',
                        displayName: 'Creation time',
                        width: 200,
                        type: 'date',
                        cellFilter: 'alpDatetimeFilter'
                    }
                ],
                //---------------api---------------------
                onRegisterApi: function (gridApi) {
                    //Page button event
                    gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
                        //Call query method
                        initGridData();
                    });
                    //row selection event
                    gridApi.selection.on.rowSelectionChanged($scope, function (row, event) {
                        if (row) {
                            if (row.isSelected) {
                                self.selectedItem = row.entity;
                                //console.log (self.selectedItem);
                            } else {
                                self.selectedItem = null;
                            }
                        }
                        let currentSelection = gridApi.selection.getSelectedRows();
                        if (currentSelection. length > 0) {
                            self.selectedItems = currentSelection;
                            self.isButtonVisible = true;

                            //console.log (self.selectedItem);
                        } else {
                            self.selectedItems = null;
                            self.isButtonVisible = false;
                        }
                    });
                    //Select all event enableSelectAll (triggered when all is selected on the grid)
                    gridApi.selection.on.rowSelectionChangedBatch($scope, function (row, event) {
                        let currentSelection = gridApi.selection.getSelectedRows();

                        if (currentSelection. length > 0) {
                            self.selectedItems = currentSelection;
                            //console.log (self.selectedItem);
                        } else {
                            self.selectedItems = null;
                        }
                        console.log("Multiple selection values-----------------", self.selectedItems);
                    });
                },
                data: []
            }
        }
        //Picture Preview
        function BtnViewImg(row) {
            var imgUrl = commonService.getMesApiAddress("ProduceManage") + row.entity.FileURL;
            console.log("row----------------", JSON.stringify(row.entity));
            console.log("imgUrl----------------", imgUrl);
            //URL of the page opened in the new window
            var newWindow = window.open(imgUrl, '_blank');
        }
        //Query method, data binding
        function initGridData() {
            self.selectedItem = null;
            self.selectedItems = null;

            self.isButtonVisible = false;
            let Pagination = {
                rows: self.gridOptions.paginationPageSize,
                page: self.gridOptions.paginationCurrentPage,
                sidx: 'CreatedOn', //Unsorted fields use primary keys
                sort: 'desc'
            };

            let queryParmeters = {
                pagination: pagination,
                queryJson: {
                    Machineid: self.Machineid
                }
            };
            console.log('queryParmeters-----' + JSON.stringify(queryParmeters));
            var url = commonService.getMesApiAddress("ProduceManage") + 'DeliveryManagement/GetDeliveryManagementFileList';
            //var url = 'http://localhost:55801/DeliveryManagement/GetDeliveryManagementFileList';
            commonService.callWebApiPost(url, queryParmeters).then(function (res) {
                //console.log ('-self.Post_ResultData----------------------' + JSON.stringify(res));
                if ((res) & amp; & amp; (res.data.success)) {
                    //Total number of items
                    self.gridOptions.totalItems = res.data.resultData.records;
                    //data
                    self.gridOptions.data = res.data.resultData.rows;
                } else {
                    self.gridOptions.data = [];
                }
            }, function (error) {
                backendService.genericError('Error getting data', "Error getting data");
            });
        }

        function addButtonHandler(clickedCommand) {
            $state.go(rootstate + '.add', {
                Machineid: self.Machineid
            });
        }

        function editButtonHandler(clickedCommand) {
            // TODO: Put here the properties of the entity managed by the service
            $state.go(rootstate + '.edit', {
                id: self.selectedItem.Id,
                selectedItem: self.selectedItem
            });
        }

        function cameraButtonHandler(clickedCommand) {
            // TODO: Put here the properties of the entity managed by the service
            $state.go(rootstate + '.camera', {
                Machineid: self.Machineid
            });
        }

        function selectButtonHandler(clickedCommand) {
            // TODO: Put here the properties of the entity managed by the service
            $state.go(rootstate + '.select', {
                id: self.selectedItem.Id,
                selectedItem: self.selectedItem
            });
        }

        //Batch delete events
        function deleteButtonHandler(clickedCommand) {
            var title = "delete";
            var text = "Confirm to delete the selected record?";
            backendService.confirm(text, function () {
                //commonService.getMesApiAddress() = '/sitSrvApi/'
                var url = commonService.getMesApiAddress("ProduceManage") + 'DeliveryManagement/RemoveDeliveryFile';
                console.log("Delete----------------" + url);
                var user = commonService.getLoginUser();
                //self.UserId = user['nameid'];
                self.UserCode = user.loginName;
                self.UserName = user.fullName;
                if (self.UserName == null || self.UserName == '' || self.UserName == undefined) {
                    self.UserName = self.UserCode;
                }
                self.selectedItem.LastUpdateUserCode = self.UserCode;
                self.selectedItem.LastUpdateUserName = self.UserName;

                let tmpData = self.selectedItems.map(t => {
                    return t.Id;
                });
                //Submit to delete the currently selected data entity
                var postData = {
                    Ids: tmpData,
                    LastUpdateUserCode: self.selectedItem.LastUpdateUserCode,
                    LastUpdateUserName: self.selectedItem.LastUpdateUserName
                };
                console.log("new postData------------------------------------" + JSON.stringify (postData));
                commonService.callWebApiPost(url, postData).then(function (res) {
                    console.log("RemoveQC_BSInspectItem----------------------------" + JSON.stringify(res));
                    if ((res) & amp; & amp; (res.data.success)) {
                        var resultData = res.data.resultData;
                        //success
                        commonService.showInfo(res.data.returnMsg);

                        self.selectedItem = null;
                        self.isButtonVisible = false;
                        $state.go(rootstate, {}, {
                            reload: true
                        });
                    } else {
                        //fail
                        commonService.showWarning(res.data.returnMsg);
                        console.log('Error deleting data: [' + res.status + '] - ' + res.statusText + '-' + res.data.returnMsg);
                        //backendService.genericError('[' + res.status + '] - ' + res.statusText + '-' + res.data.returnMsg, "Error deleting data");
                    }
                }, function (error) {
                    console.log("RemoveQC_BSInspectItem--error--------------------------" + JSON.stringify(error));
                    backendService.genericError('[' + error.status + '] - ' + error.statusText + '-' + error.data.returnMsg, "Error getting data");
                });
            }, title);
        }

        function onGridItemSelectionChanged(items, item) {
            if (item & amp; & amp; item.selected == true) {
                self.selectedItem = item;
                setButtonsVisibility(true);
            } else {
                self.selectedItem = null;
                setButtonsVisibility(false);
            }
        }
        // Internal function to make item-specific buttons visible
        function setButtonsVisibility(visible) {
            self.isButtonVisible = visible;
        }
    }

    ListScreenRouteConfig.$inject = ['$stateProvider'];

    function ListScreenRouteConfig($stateProvider) {
        var moduleStateName = 'home.Nancanl_PR_ProductAPP_DeliveryFile';
        var moduleStateUrl = 'Nancanl.PR_ProductAPP_DeliveryFile';
        var moduleFolder = 'Nancanl.PR.ProductAPP/modules/DeliveryFile';

        var state = {
            name: moduleStateName + '_DeliveryFile',
            url: '/' + moduleStateUrl + '_DeliveryFile',
            views: {
                'Canvas@': {
                    templateUrl: moduleFolder + '/DeliveryFile-list.html',
                    controller: ListScreenController,
                    controllerAs: 'vm'
                }
            },
            params: {
                Id: null,
                selectedItem: null,
            },
            data: {
                title: 'Shipping photo management'
            }
        };
        $stateProvider.state(state);
    }
}());