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

时间:2015-04-09 08:41:23

标签: javascript html angularjs transpose

我有三个对象:

用户

[
    {
        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'
    },
]

我需要做的是显示组合数据的单个表,但表必须能够转置并且我需要能够编辑每个单元格的值(权限),并且变化应该反映在任何地方。

这是当前的原型,所以你看它应该是什么样子:

enter image description here enter image description here

目前我创建两个单独的对象,其中包含填充每个表的数据,然后只显示/隐藏表(转置)。这是相当复杂的并且不容易因为我需要能够编辑单元格中的值并需要更改以反映转置。

我将不胜感激任何建议如何做得更好。

1 个答案:

答案 0 :(得分:1)

有趣的问题。放手一搏:

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;
};

});

在这里工作小提琴:https://jsfiddle.net/kyp7nvng/5/