Angular ui-grid - 下拉选择显示 Id

Anu*_*nup 1 jquery angularjs angular-ui-grid

我正在使用 Angular http://ui-grid.info/。当我在网格中有下拉菜单时遇到问题。

以下代码我用于 DropDown :-

objCombos = $scope.getComboValues('DEPARTMENT');

$scope.gridOptions.columnDefs.push({
field: fieldName.toUpperCase(), displayName: displayName,
columnType: 'columnDb',
editableCellTemplate: 'ui-grid/dropdownEditor',
editDropdownValueLabel: 'DEPARTMENT',
editDropdownOptionsArray: objCombos,
name: fieldName.toUpperCase()
});
Run Code Online (Sandbox Code Playgroud)

DropDown 的数组是这样的objCombos:-

[
    { id: 1, department: 'Branch1' },
    { id: 2, department: 'Branch2' }
];
Run Code Online (Sandbox Code Playgroud)

当我选择并更改下拉值时说从Branch1Branch2,更改值后,id在这种情况下,它会显示下拉列表中所选值的值2

在此处输入图片说明

Tre*_*hek 5

对于实际上不需要 id 的情况,将设置editDropdownIdLabel为匹配editDropdownValueLabel是可以的。也就是说,您的底层数据结构存储字符串(“Branch1”、“Branch2”)而不是整数(1,2)。

如果不是这种情况,请使用自定义过滤器。我最近遇到了一种情况,一周中的天数以整数 (1-7) 的形式存储在后端,但用户希望在网格中看到全名字符串。以下是我的解决方案 - 针对此示例进行了修改:

angular.module('myApp').filter("branchFilter", function() {
    var vals = ["Branch1", "Branch2"];
    return function(id) {
        var i = id-1, ret = "?";
        if(i>=0 && i< vals.length) {
            ret = vals[i];
        }
        return ret;
    };
});
Run Code Online (Sandbox Code Playgroud)

然后在 columnDefs 中,添加cellFilter: 'branchFilter'.

话虽如此,令人讨厌的是 ui-grid 假设您需要在下拉列表中区分idvalue,但随后显示 id,除非在编辑时。很难想象这种行为对用户有用的情况。

我注意到您将组合值存储在一个单独的数组中。这是一种重用此结构的方法。首先,将组合值放在可以在整个应用程序中访问的位置:

angular.module('myApp').value('ComboValues', {
    branches: [
        {id:1, value:"Branch1"},
        {id:2, value:"Branch2"},
        ...
    ]
});
Run Code Online (Sandbox Code Playgroud)

然后告诉自定义过滤器如何使用这些值:

angular.module('myApp').filter("comboFilter", function(ComboValues) {
    return function(id, comboName, idName, valName) {
        idName = idName || "id";      //optional - defaults to 'id'
        valName = valName || "value"; //optional - defaults to 'value'
        var opts = ComboValues[comboName];
        if(angular.isArray(opts)) {
            var ret = id; //default return value if no match found
            opts.some(function(opt) {  //look for matching option
                if(opt[idName]===id) {
                    ret = opt[valName];
                    return true; //break
                }//else keep looking
            });
            return ret;
        } else {
            return comboName+ " not an array";
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

然后在 columnDefs 中,使用: cellFilter: "comboFilter:'branch':'id':'value'" 或者如果默认值没问题: cellFilter: "comboFilter:'branch'"

请注意,在此示例中,参数需要额外的引号,因此过滤器将它们视为字符串而不是范围变量。那就是:"comboFilter:'branch'"不是"comboFilter:branch"