Angularjs controller for multiple views

VivekDev

If I need to reuse the following controller(placed in App.js), I need to remove the view specific columnDefs and place them separately(View, html file).

Here I have ui-grid's gridOptions set in the controller itself. Even if I manage to place that in UI(script tag), uiGridConstants is not available in the view. So how do I go about with this so I may reuse the file for multiple views. I am pulling my hair for quite some time now, and am a newbie on angular, so please help.

(function () {
    gridFactory = function ($http) {
        return {
            callWebApi: function () {
                return $http({
                    method: 'GET',
                    url: '/api/PatientCategoryApi/PatCat',
                    params: this.callParams.paginationOptions,
                    headers: { 'Content-Type': 'application/Json' }
                })
            },
            callParams: {}
        }
    };
    patientCategoryController = function ($scope, $attrs, uiGridConstants, gridFactory) {

        $scope.gridOptions = {

            paginationPageSizes: [5, 10, 20, 25, 50],
            paginationPageSize: 10,
            useExternalPagination: true,
            useExternalSorting: true,
            enableSorting: true,
            rowHeight: 30,
            columnDefs: [
                { field: 'Id', sortDirectionCycle:[uiGridConstants.ASC, uiGridConstants.DESC] },
                { field: 'Code' },
                { field: 'Name' },
                { field: 'Description' },
                { field: 'ModifiedTime', cellFilter: 'date:"dd-MMM-yy h:mm:ss a"' },
                { field: 'History', enableSorting: false }
            ],
            onRegisterApi: function (gridApi) {
                $scope.gridApi = gridApi;
            }
        };

        var callData = {};

        var paginationOptions = {};
        paginationOptions.Page = 1;
        paginationOptions.Take = 10;
        paginationOptions.SortOrder = 'Asc';
        paginationOptions.PropName = 'Id';
        callData.paginationOptions = paginationOptions;
        gridFactory.callParams = callData;
        var promise = gridFactory.callWebApi();
        promise.then(
            function successCallback(response) {
                $scope.gridOptions.totalItems = response.data.TotalCount;
                $scope.gridOptions.data = response.data.Collection;
                $scope.gridHeight = gridFactory.getGridHeight($scope.gridOptions);
            }, function errorCallback(response) {
                alert('Some problem while fetching data!!');
            });
    }
    patientCategoryController.$inject = ['$scope', '$attrs', 'uiGridConstants', 'gridFactory'];
    gridFactory.$inject = ['$http'];
    angular.module('abvhHisApp', ['ui.grid', 'ui.grid.autoResize', 'ui.grid.pagination', 'ui.grid.resizeColumns']);
    angular.module('abvhHisApp').controller('patientCategoryController', patientCategoryController);
    angular.module('abvhHisApp').factory('gridFactory', gridFactory);
}());
Constantine Poltyrev

I had exactly the same problem having a number of grid views and wanted to write DRY code. My solution was to create a base class for the grid controllers and inherit it for different views.

Base class (providing infinite scrolling for the grid):

function InfiniteGrid() {
        var vm = this;

        vm.firstPage = vm.lastPage = 1;
        vm.keepPages = 3;
        vm.pageSize = 100;
        vm.totalCount = 0;

        vm.init();

        vm.data = vm.loadData();

        vm.uiGridOptions = {
            enableSorting: true
            ,columnDefs: vm.columnDefs
            ,data: 'vm.data'
            ,infiniteScrollRowsFromEnd: 1
            ,infiniteScrollUp: true
            ,infiniteScrollDown: true
            ,onRegisterApi: function(gridApi){
                gridApi.infiniteScroll.on.needLoadMoreData(vm.$scope, vm.getDataDown);
                gridApi.infiniteScroll.on.needLoadMoreDataTop(vm.$scope, vm.getDataUp);
                vm.gridApi = gridApi;
            }
        };

        vm.$scope.$watch('vm.filterText', function(search){
            vm.firstPage = vm.lastPage = 1;
            vm.data = vm.loadData(1, search);
        });

    }

    InfiniteGrid.prototype = {
        loadData : function (page, search) {
            var vm = this;
            return vm.Entity.query({page: page, limit: vm.pageSize, search: search}, function (data, headers) {
                vm.totalCount = data.total_count = 1 * headers('X-List-Total');
                vm.$timeout(function () {
                    vm.gridApi.infiniteScroll.dataLoaded(vm.firstPage > 1, vm.lastPage < Math.floor(vm.totalCount / vm.pageSize) + 1);
                });
            });
        },
        getDataDown : function () {
            var gridApi = this,
                vm = gridApi.grid.appScope.vm;
            vm.loadData(vm.lastPage + 1).$promise.then(function (newData) {
                vm.lastPage++;
                gridApi.infiniteScroll.saveScrollPercentage();
                vm.data = vm.data.concat(newData);
                gridApi.infiniteScroll.dataLoaded(vm.firstPage > 1, vm.lastPage < Math.floor(newData.total_count / vm.pageSize) + 1)
                    .then(vm.checkDataLength.bind(vm, 'up'));
            });
        },

        getDataUp : function () {
            var gridApi = this,
                vm = gridApi.grid.appScope.vm;
            vm.loadData(vm.firstPage - 1).$promise.then(function (newData) {
                vm.totalCount = newData.total_count;
                vm.firstPage--;
                gridApi.infiniteScroll.saveScrollPercentage();
                vm.data = newData.concat(vm.data);
                gridApi.infiniteScroll.dataLoaded(vm.firstPage > 1, vm.lastPage < Math.floor(newData.total_count / vm.pageSize) + 1)
                    .then(vm.checkDataLength.bind(vm, 'down'));
            });
        },

        checkDataLength : function (direction) {
            var vm = this;
            if (vm.lastPage - vm.firstPage > vm.keepPages) {
                if (direction === 'up') {
                    vm.data = vm.data.slice(vm.pageSize);
                    vm.firstPage++;
                    vm.$timeout(function () {
                        vm.gridApi.infiniteScroll.dataRemovedTop(vm.firstPage > 1, vm.lastPage < Math.floor(vm.totalCount / vm.pageSize) + 1);
                    });
                } else {
                    vm.data = vm.data.slice(0, vm.pageSize * vm.keepPages);
                    vm.lastPage--;
                    vm.$timeout(function () {
                        vm.gridApi.infiniteScroll.dataRemovedBottom(vm.firstPage > 1, vm.lastPage < Math.floor(vm.totalCount / vm.pageSize) + 1);
                    });
                }
            }
        },

        deleteRow : function (rowId) {
            var vm = this,
                row = vm.$filter('filter')(vm.data, {_id: rowId})[0],
                rowIdx = vm.data.indexOf(row);

            vm.Entity.delete({id: rowId}).$promise.then(function () {
                vm.data.splice(rowIdx, 1);
                vm.toastr.success("Record successfully deleted!", "Success", {extendedTimeOut: 1500, timeOut: 1500});
            }, function (data, status) {
                if (status !== 401) {
                    vm.toastr.error(data.data.message);
                }
            });
        }
    };

    return InfiniteGrid;
});

Inherited controller code

angular.module('myApp')
        .controller('SomeGridCtrl', ['$scope', '$timeout', '$resource', 'toastr', '$filter', '$routeParams', SomeGridCtrl]);

    function SomeGridCtrl($scope, $timeout, $resource, toastr, $filter, $routeParams)
    {
        var vm = this;
        $scope.vm = vm;
        vm.$scope = $scope;
        vm.toastr = toastr;
        vm.$filter = $filter;
        vm.$timeout = $timeout;
        vm.$resource = $resource;
        vm.$routeParams = $routeParams;

        // Call the parent constructor
        infiniteGrid.call(vm);
    }

    // Inherit the prototype
    SomeGridCtrl.prototype = Object.create(infiniteGrid.prototype);

    SomeGridCtrl.prototype.init = function() {
        var vm = this;

        vm.Entity = vm.$resource('/api/item/:id');
        vm.columnDefs = [
            {
                displayName: "Title"
                ,field: "title"
                //,filter: 'text',
                ,cellTemplate: '<div class="ui-grid-cell-contents"><a ng-href="#/card/{{ row.entity._id }}" ng-bind="COL_FIELD"></a></div>'
            },{
                displayName: "URL"
                ,field: "url"
                ,filter: 'text'
                ,cellTemplate: '<div class="ui-grid-cell-contents"><a ng-href="#/card/{{ row.entity._id }}" ng-bind="COL_FIELD"></a></div>'
            },{
                displayName: "Partner"
                ,field: "partner.fullName"
                //,filter: 'text'
            },{
                field: 'review_count'
                ,displayName: 'Reviews'
                ,width: 80
                ,cellTemplate: '<div class="ui-grid-cell-contents"><a ng-href="#/card/{{ row.entity._id }}/reviews" ng-bind="COL_FIELD"></a></div>'
            },{
                displayName: "Created on"
                ,field: 'created'
                ,cellFilter: 'amCalendar'
                ,filter: false
            },{
                displayName: "Delete"
                ,field: "dummy"
                //,width: 80
                ,cellTemplate: '<div class="ui-grid-cell-contents"><a ng-click="grid.appScope.vm.deleteRow(row.entity._id)" confirm="Are you sure?" class="btn btn-xs btn-danger">Delete</a></div>'
            }
        ];
    };

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Angularjs controller for multiple views

From Dev

Controlling multiple views in one controller in AngularJS

From Dev

Controlling multiple views in one controller in AngularJS

From Dev

Controller in Nested views of AngularJS

From Dev

Controller in Nested views of AngularJS

From Dev

AngularJS directive multiple views

From Dev

ngRoute in angularjs/multiple views

From Dev

How can I use multiple angularjs's controller inside a view (or subview of a multi-views)?

From Dev

multiple controller not working in angularjs

From Dev

Responsibility of a controller in AngularJS - More than two views?

From Dev

angularjs using single controller with two views

From Dev

AngularJS Directive or Controller to seperate views components

From Dev

How to redirect views using the same angularjs controller?

From Dev

UI-Router Multiple Views Single Controller

From Dev

Multiple Views 1 View Controller transition animation

From Dev

Angular JS controller scope, multiple views

From Dev

AngularJs multiple instances and nested controller

From Dev

Multiple ng-views for homepage in angularjs

From Dev

AngularJS Multiple Dynamic Views based on Single Route

From Dev

angularjs - ui-router multiple nested views

From Dev

Using multiple views in the same page using AngularJS

From Dev

AngularJS Multiple views with shared logic design pattern

From Dev

Can I use one controller updating two views in AngularJS?

From Dev

Angularjs: ui-router controller in views throws error

From Dev

Resolving values for each controller, when using multiple views

From Dev

How can I reuse a controller for multiple partial views?

From Dev

UI-Router Multiple Views Single Controller not work

From Dev

ui-router nested views access to multiple controller

From Dev

How can I have multiple Collection Views in one View Controller?

Related Related

  1. 1

    Angularjs controller for multiple views

  2. 2

    Controlling multiple views in one controller in AngularJS

  3. 3

    Controlling multiple views in one controller in AngularJS

  4. 4

    Controller in Nested views of AngularJS

  5. 5

    Controller in Nested views of AngularJS

  6. 6

    AngularJS directive multiple views

  7. 7

    ngRoute in angularjs/multiple views

  8. 8

    How can I use multiple angularjs's controller inside a view (or subview of a multi-views)?

  9. 9

    multiple controller not working in angularjs

  10. 10

    Responsibility of a controller in AngularJS - More than two views?

  11. 11

    angularjs using single controller with two views

  12. 12

    AngularJS Directive or Controller to seperate views components

  13. 13

    How to redirect views using the same angularjs controller?

  14. 14

    UI-Router Multiple Views Single Controller

  15. 15

    Multiple Views 1 View Controller transition animation

  16. 16

    Angular JS controller scope, multiple views

  17. 17

    AngularJs multiple instances and nested controller

  18. 18

    Multiple ng-views for homepage in angularjs

  19. 19

    AngularJS Multiple Dynamic Views based on Single Route

  20. 20

    angularjs - ui-router multiple nested views

  21. 21

    Using multiple views in the same page using AngularJS

  22. 22

    AngularJS Multiple views with shared logic design pattern

  23. 23

    Can I use one controller updating two views in AngularJS?

  24. 24

    Angularjs: ui-router controller in views throws error

  25. 25

    Resolving values for each controller, when using multiple views

  26. 26

    How can I reuse a controller for multiple partial views?

  27. 27

    UI-Router Multiple Views Single Controller not work

  28. 28

    ui-router nested views access to multiple controller

  29. 29

    How can I have multiple Collection Views in one View Controller?

HotTag

Archive