【问题标题】:Where should I put my ag-grid code?我应该把我的 ag-grid 代码放在哪里?
【发布时间】:2016-11-01 19:07:17
【问题描述】:

我有一个视图,其中包含一个 ag-grid 和一个用于我的 Angular 应用程序的控制器。我正在尝试清理控制器,使其“变薄”,并且我已经在指令中移走了一些代码,并且我已经为数据检索设置了服务。

现在我留下了一个关于 ag-grid 代码的大型博客,理想情况下我希望看到它出现在其他地方,但我不确定哪里是最好的地方。

这里有最佳实践吗?

<div class="container" ng-controller="MainController">

<div class="row">
    <div class="col-sm-4">
        <div>
            <div ag-grid="gridOptions" class="ag-fresh" style="height: 500px; width: 100%"></div>
        </div>
    </div>
    <div class="col-sm-8">
        <div my-directive body-unid="currentUNID"></div>
    </div>
</div>

agGrid.initialiseAgGridWithAngular1(angular);

angular.module('app') .controller('MainController', function ($scope, myService, MyConfig) {

    $scope.isExternalFilterPresent = function () {
        return $scope.searchtext != "";
    };

    $scope.doesExternalFilterPass = function (node) {

        // Returning true means all the documents are displayed
        if ($scope.searchtext == "") {
            return true;
        }

        if ($scope.joinedUnidsOfSearch) {
            return ($scope.joinedUnidsOfSearch.indexOf(node.data['@unid']) >= 0);
        } else {
            return true;
        }
    };

    var columnDefs = [
        {
            headerName: "Navigation", field: "Subject", cellStyle: function (params) {
            if (params.data["@indent"]) {
                switch (params.data["@indent"]) {
                    case 1:
                        return {'margin-left': '10px'};
                        break;
                    case 2:
                        return {'margin-left': '20px'};
                        break;
                    case 3:
                        return {'margin-left': '30px'};
                        break;
                    case 4:
                        return {'margin-left': '40px'};
                        break;
                    default:
                        return {'margin-left': '50px'};
                        break;
                }
            } else {
                return {'font-size': 'large'};
            }
        }
            //, headerName: "unid", field: "@unid"
        }
    ];

    $scope.gridOptions = {
        columnDefs: columnDefs,
        rowSelection: 'single',
        enableFilter: true,
        isExternalFilterPresent: $scope.isExternalFilterPresent,
        doesExternalFilterPass: $scope.doesExternalFilterPass,

        angularCompileRows: true,
        onRowClicked: function (event) {
            //console.log('a row was clicked', event.data["@unid"]);
            $scope.currentUNID = event.data["@unid"];
            $scope.$apply();
        },
        onColumnResized: function (event) {
            //console.log('a column was resized');
        },
        onGridReady: function (event) {
            //console.log('the grid is now ready');
        },

        // onRowSelected: rowSelected,
        // onSelectionChanged: onSelectionChanged,

        onGridSizeChanged: function () {
            //console.log('Grid Size changed');
            $scope.gridOptions.api.sizeColumnsToFit();
        }
    };

    $scope.databaseTitle = MyConfig.databaseTitle;

    $scope.SearchButtonClick = function () {
        $scope.searchComment = '';
        loadSearchResults($scope);
    };

    $scope.ClearSearchBox = function () {
        $scope.searchtext = '';
        $scope.searchComment = '';
        $scope.gridOptions.api.onFilterChanged();
    };


    $scope.NextButtonClick = function () {
        //console.log("next button clicked");
        var selectedNodes = $scope.gridOptions.api.getSelectedNodes();
        if (selectedNodes) {
            if (selectedNodes && selectedNodes.length === 1) {
                var selectedNode = selectedNodes[0];
                $scope.gridOptions.api.forEachNodeAfterFilter(function (node) {
                    if (node.childIndex === (selectedNode.childIndex + 1)) {
                        node.setSelected(true);
                        $scope.currentUNID = node.data["@unid"];
                        return;
                    }
                });
            }
        }
    };

    $scope.PrevButtonClick = function () {
        //console.log("next button clicked");
        var selectedNodes = $scope.gridOptions.api.getSelectedNodes();
        if (selectedNodes) {
            if (selectedNodes && selectedNodes.length === 1) {
                var selectedNode = selectedNodes[0];
                $scope.gridOptions.api.forEachNodeAfterFilter(function (node) {
                    if (node.childIndex === (selectedNode.childIndex - 1)) {
                        node.setSelected(true);
                        $scope.currentUNID = node.data["@unid"];
                        return;
                    }
                });
            }
        }
    };

    function loadSearchResults($scope) {
        //console.log('loadSearchResults started');
        if ($scope.searchtext) {
            myService.loadAllUNIDSThatMatchSearch($scope.searchtext).then(function (data) {
                //console.log('start after loading of search UNIDS');
                var receiveddata = angular.fromJson(data);
                if (receiveddata) {
                    if (receiveddata.length > 0) {
                        $scope.searchComment = '';
                        var arrayUNIDS = receiveddata.map(function (a) {
                            return a["@unid"];
                        });
                        $scope.joinedUnidsOfSearch = arrayUNIDS.join(); // this variable gets used in the function doesExternalFilterPass
                        $scope.gridOptions.api.onFilterChanged(); // refreshes filter of grid
                        // set the selected document to the first of the search query
                        $scope.gridOptions.api.forEachNodeAfterFilter(function (node) {
                            if (node.firstChild === true) {
                                // node.setSelected(true);
                                $scope.gridOptions.api.selectNode(node, true);
                                $scope.currentUNID = node["@unid"];
                            }
                        });
                    } else {
                        if ($scope.searchtext == '' || $scope.searchtext == undefined) {
                            $scope.searchComment = 'Das Suchfeld ist leer!';
                        } else {
                            $scope.searchComment = 'Keine Dokumenten für ' + $scope.searchtext + ' gefunden.';
                        }


                    }
                }
                //console.log('end after loading of search UNIDS');
            });
        }
        //console.log('loadSearchResults ended');
    }

    myService.loadAllNavigationDocuments()
        .then(function (response) {
            $scope.gridOptions.api.setRowData(response);
        });


});

【问题讨论】:

  • 你能分享一些代码吗?我总是为此使用角度组件。
  • 完成。我知道现在很丑!
  • 我试图将代码移到另一个控制器中,但是我遇到了访问 $scope 时遇到问题的问题

标签: angularjs ag-grid


【解决方案1】:

现在,看到您的代码,我认为您可以将所有网格内容移动到服务中。 在服务中创建方法,然后像这样在您的控制器中调用:

//create the event "onGridSizeChanged" for the grid
gridService.onGridSizeChanged($scope.gridOptions, fuction(options){
   //callback for size changed
});

只是一个例子,所以创建你需要的所有其他方法。您的控制器将是干净的,您可以在其他控制器中使用该服务。这种方法只有一个职责,并且易于维护。

【讨论】:

  • 所以我要在我的控制器中定义 gridOptions?
  • 是的,您在控制器中定义了 gridOptios 并在 Angular 服务中处理其他方法和事件。
  • 我已经成功地将 columnDefs 放入我的服务中,但是我正在阻止例如使用函数 doesExternalFilterPass。它需要一个节点参数,一旦我将函数移动到服务中,我就会抱怨 $scope 未知。我想我在这里遗漏了一些非常基本的东西。
  • 我认为那些函数 doesExternalFilterPassisExternalFilterPresent 不是网格上使用的函数吗?如果没有,则在 $scope 而不是 gridOptions 中创建 then。为网格属性/方法保留 gridOptions
  • 它们是用于过滤的gridOptions的成员
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-25
  • 2020-09-30
相关资源
最近更新 更多