有没有办法自动调整ng-grid的宽度?

Riz*_*Riz 24 ng-grid

我的列宽度有问题.我不知道它们预先的宽度,也不想指定每列的宽度.是否有可以使用的属性根据内容(包括列标题)自动调整所有列宽?

Jes*_*ess 12

活泉!我想出了一个很酷的答案!设置宽度"auto"对我来说真的不起作用.也许是因为我正在使用ng-view?不确定.所以我创建了2个可以放入你的新功能controller.js.像这样使用它们会给你计算列宽!阅读代码注释; 有一些警告.

示例用法,controllers.js:

var colDefs = makeColDefs(rows[0]);
colDefs = autoColWidth(colDefs, rows[0]);

$scope.phones = rows;
$scope.gridOptions = {
    data : 'phones',
    showFilter : true,
    enableColumnResize : true,
    columnDefs : colDefs
};
Run Code Online (Sandbox Code Playgroud)

代码,controllers.js:

/**
 * Create a colDefs array for use with ng-grid "gridOptions". Pass in an object
 * which is a single row of your data!
 */
function makeColDefs(row) {
    var colDefs = [];
    for ( var colName in row) {
        colDefs.push({
            'field' : colName
        });
    }
    return colDefs;
}

/**
 * Return a colDefs array for use with ng-grid "gridOptions". Work around for
 * "auto" width not working in ng-grid. colDefs array will have percentage
 * widths added. Pass in an object which is a single row of your data! This
 * function does not do typeface width! Use a fixed width font. Pass in an
 * existing colDefs array and widths will be added!
 */
function autoColWidth(colDefs, row) {
    var totalChars = 0;
    for ( var colName in row) {
        // Convert numbers to strings here so length will work.
        totalChars += (new String(row[colName])).length;
    }
    colDefs.forEach(function(colDef) {
        var numChars = (new String(row[colDef.field])).length;
        colDef.width = (numChars / totalChars * 100) + "%";
    });
    return colDefs;
}
Run Code Online (Sandbox Code Playgroud)

Jasmine测试,controllerSpec.js:

'use strict';

var ROW = {
    'col1' : 'a',
    'col2' : 2,
    'col3' : 'cat'
};
var COLUMN_DEF = [ {
    field : 'col1'
}, {
    field : 'col2'
}, {
    field : 'col3'
} ];
var COLUMN_DEF2 = [ {
    field : 'col1',
    width : '20%'
}, {
    field : 'col2',
    width : '20%'
}, {
    field : 'col3',
    width : '60%'
} ];

/* jasmine specs for controllers go here */

describe('controllers', function() {
    beforeEach(module('myApp.controllers'));

    it('should make an ng-grid columnDef array from a row of data.',
            function() {
                expect(makeColDefs(ROW)).toEqual(COLUMN_DEF);
            });

    it('should return an ng-grid columnDef array with widths!', function() {
        var colDefs = makeColDefs(ROW);
        expect(autoColWidth(colDefs, ROW)).toEqual(COLUMN_DEF2);
    });

});
Run Code Online (Sandbox Code Playgroud)


Mar*_*yer -1

是的!您columndefs可以将宽度设置为auto,这将根据数据和/或标题的宽度自动调整列的大小。

参考:定义列

  • 这不起作用。以下是您提供的链接的引用:_注意:“auto”目前仅适用于单页应用程序,因为调整大小发生在“document.ready”上。仍在努力改进这一点。”_ (4认同)