具有不同对象属性的表的自定义指令
Custom Directive for Table with different object properties
假设我想编写一个可重用的+通用指令,该指令将在整个项目中使用。该指令将显示一个表格,如下所示:
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个属性,即Id
、ProductNo
等。但在我的表中,我只想显示其中的2个,比如说只有ProductNo
和BasePrice
。如何丢弃我不想要的另外两个属性?正如你从我的部分模板中看到的,我使用的是双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>'
相关文章:
- 如何在自定义指令中获取计算的属性
- 向动态生成的DOM添加Angular自定义指令
- 自定义指令中的AngularJS ng模型
- 如何在html中以角度显示自定义指令的作用域
- 自定义指令模板中的AngularJS控制变量
- AngularJS通过自定义指令传递点击的项目
- 如何在angularjs中将多个作用域变量传递到自定义指令中
- 处理角度自定义指令中的onReady事件
- 为什么ng中的自定义指令在循环完成后重复运行
- 对于使用传递的数据计算的局部范围变量,角度绑定在自定义指令中不起作用
- Angular.JS自定义指令;不起作用
- 如何通过Angular中的$resource发送来自自定义指令的输入值
- AngularJS:如何访问自定义指令中的input[date]min属性
- AngularJS:ngRepeat作用域在具有隔离作用域和ngTransclude的自定义指令中失败
- 如何使用其他自定义指令中的元素标记作为另一个自定义指令的模板
- 如何限制自定义指令的可能属性值
- 动态网格作为自定义指令
- AngularJS - 在自定义指令中继承ngModel
- 调用另一个自定义指令的角度自定义指令
- 在 AngularJs 中验证自定义指令(我想让它成为必需的)