具有不同对象属性的表的自定义指令

Custom Directive for Table with different object properties

本文关键字:自定义 指令 属性 对象      更新时间:2023-09-26

假设我想编写一个可重用的+通用指令,该指令将在整个项目中使用。该指令将显示一个表格,如下所示:

angular
    .module('demo')
    .directive('indexTable', function() {
        return {
            restrict: 'A',
            template: '<tr ng-repeat=" component in components>' +
                        '<td ng-repeat="obj in component">' +
                          '{{obj}}' + 
                        '</td>' + 
                       '</tr>',
            scope: {
                 components: '=',
            },
            link: function (scope, attrs) {
            }
        }
    });

假设在我的控制器中,我有两个不同的数组,每个数组有两组不同属性的不同对象:

//some mockup data
angular.module('demo')
   .controller('demoCtrl',['$scope',function($scope){
    //array 1
    $scope.userArray = [
      {Id:1 , Name: 'Chuck Norris', Age:'21'},
      {Id:2 , Name: 'George Bush' , Age: '42'}
    ];
    //array 2 
    $scope.itemArray = [
      {Id:1, ProductNo: '001', BasePrice: 20.20, Value: 50.50} 
      {Id:2, ProductNo: '002', BasePrice: 20.20, Value: 50.50} 
    ];
}]);

所以基本上问题是:我如何选择(在控制器中)要在表中显示的属性?

深度问题:现在我有两个不同的数组,每个数组都有自己的属性。我将如何在我的HTML中使用它将是

<div index-table components="userArray"></div>

itemArray为例。每个对象将有4个属性,即IdProductNo等。但在我的表中,我只想显示其中的2个,比如说只有ProductNoBasePrice。如何丢弃我不想要的另外两个属性?正如你从我的部分模板中看到的,我使用的是双ng-repeats

到目前为止,我已经考虑过/尝试过:尝试过将对象映射到数组,但我相信ng-repeat要智能得多。我需要添加更多的作用域属性吗?如何编写链接函数?有什么想法吗?

您可以传递一个属性,定义将填充每列的属性名称。例如:

<table index-table
    components="itemArray"
    columns="ProductNo,BasePrice"
></table>

您的指令必须稍作修改:

app.directive('indexTable', function() {
    function parseProps(str) {
        // implement parse logic, return an array of strings - the property names
    }
    return {
        restrict: 'A',
        template:
            '<tr ng-repeat="component in components">' +
                '<td ng-repeat="name in props">' +
                    '{{ component[name] }}' + 
                '</td>' + 
            '</tr>',
        scope: {
            components: '='
        },
        link: function (scope, elem, attrs) {
            scope.props = parseProps(attrs.columns);
        }
    };
});

您可以在这里看到一个示例实现:http://jsfiddle.net/y54x0hcd/

这有很多粗糙的边缘(例如:专栏标题?);也许使用网格库会更好。

为什么不将要显示的属性传递给指令?然后你的ng重复会看起来像这样:

                    '<td ng-repeat="obj in component">'
                      '{{obj[passedInDisplayKey]}}'
                    '</td>'