我需要以角度创建独立的网格指令。数据和动作将在控制器中设置。动作可以引用其他控制器或父控制器中的其他动作。两者都是可能的。
这是现场示例:http ://plnkr.co/edit/efe4notoE1TyONH3W347?p=preview
在 index.html 中
<body ng-controller="MainCtrl">
<div grid data="data" action-list="actionList" call="call(fun, row)"></div>
</body>
控制器
app.controller('MainCtrl', function($scope) {
$scope.data = [
{id: 1, name: 'aaa'},
{id: 2, name: 'bbb'},
{id: 3, name: 'ccc'}
];
// actions (show, delete) have to be defined before $scope.actionList
$scope.show = function (row) {
alert('show: ' + row.id + ':' + row.name);
}
$scope.delete = function (row) {
alert('delete: ' + row.id);
}
$scope.actionList = [
{ label: 'edit', href: '#/edit/{{row.id}}', title: 'to other CTRL' },
{ label: 'show', click: $scope.show, title: 'use ngClick' },
{ label: 'delete', click: $scope.delete, title: 'use ngClick' }
];
// call any action in this CTRL
$scope.call = function (fun, row) {
fun(row);
}
});
网格指令。参数call
将用于将所有动作功能传递给控制器。hrefCompiled
动作汇编href
(例如#/edit/{{row.id}}
)
app.directive('grid', function () {
return {
scope: {
data: '=',
actionList: '=',
call: '&'
},
//
controller: function ($scope, $interpolate) {
$scope.hrefCompiled = function (action, row) {
if (action.href) {
return $interpolate(action.href)({row: row})
}
return '';
}
},
templateUrl: 'grid.html'
}
});
网格.html
<table>
<tr>
<th ng-repeat="(key, value) in data[0]">{{key}}</th>
<th>actions</th>
</tr>
<tr ng-repeat="row in data">
<td>{{row.id}}</td>
<td>{{row.name}}</td>
<td>
<span ng-repeat="action in actionList">
<a href="{{hrefCompiled(action, row)}}"
ng-click="call({fun: action.click, row: row})"
title="{{action.title}}">{{action.label}}</a>
</span>
</td>
</tr>
</table>
这是现场示例:http ://plnkr.co/edit/efe4notoE1TyONH3W347?p=preview
可能这不是最佳实践,但它有效。请帮助我改进它。谢谢。