从三个对象创建转置 table 的有效方法

Effective way to create transposing table from three objects

我有三个对象:

用户

[
    {
        id: 1,
        name: 'User'
    },
    {
        id:2,
        name: 'User2'
    }
]

页数

[
    {
        id: 1,
        name: 'Page'
    },
    {
        id:2,
        name: 'Page2'
    }
]

权利

[
    {
        user_id: 1,
        page_id: 1,
        access: 'rw'
    },
    {
        user_id: 1,
        page_id: 2,
        access: 'ro'
    },
    {
        user_id: 2,
        page_id: 1,
        access: 'rw'
    },
]

我需要做的是显示单个 table 组合数据但是 table 必须能够转置并且我需要能够编辑每个单元格的值(权限)和更改应反映在所有地方。

这是当前的原型,您可以看到它应该是什么样子:

目前我创建了两个单独的对象,每个对象都填充了 table 的数据,然后只是 show/hide table 的数据(转置)。这相当复杂且不易处理,因为我需要能够编辑单元格中的值并需要更改以反映在转置中。

如有任何改进建议,我将不胜感激。

有趣的问题。试一试:

Html:

<div ng-app="app">
<div ng-controller="mainController">
    <button ng-click="transposeTable()">Transpose</button>

    <table>
        <thead>
            <tr>
                <td>Filter users</td>
                <td ng-repeat="col in (usersFirst ? users : pages)">{{col.name}}</td>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="row in (usersFirst ? pages : users)">
                <td>{{row.name}}</td>
                <td ng-repeat="col in (usersFirst ? users : pages)">{{usersFirst ? getRight(col, row) : getRight(row, col)}}</td>
            </tr>
        </tbody>
    </table>

</div>
</div>

Javascript:

var appModule = angular.module('app', []);

appModule.controller('mainController', function($scope) {

$scope.users = [{ id: 1, name: 'User1' }, { id:2, name: 'User2' }];
$scope.pages = [{ id: 1, name: 'Page1' }, { id:2, name: 'Page2' }];
$scope.rights = [{ user_id: 1, page_id: 1, access: 'rw' }, 
    { user_id: 1, page_id: 2, access: 'ro' }, 
    { user_id: 2, page_id: 1, access: 'rw' }, 
    { user_id: 2, page_id: 2, access: 'no' }];

$scope.usersFirst = true;
$scope.transposeTable = function() {
    $scope.usersFirst = !$scope.usersFirst;
};
$scope.getRight = function(user, page) {
    return _.find($scope.rights, function(right) {
        return right.user_id === user.id && right.page_id === page.id;
    }).access;
};

});

在这里 fiddle 工作:https://jsfiddle.net/kyp7nvng/5/