我想创建一个从数组生成完整表格的指令,提供特定的 onMouseOver 行为,并且当单击单元格时,强调具有相同值的所有单元格(以及其他特定行为)对于这个例子来说并不重要)。
// AngularJS controller
$scope.myArrayOfValues = [[0,1,2,3,4],[5,6,7,8,9]];
// Page HTML
<my-table-directive values='myArrayOfValues'></my-table-directive>
我考虑过以下方法,但我不确定它们是否是解决此类问题的最佳实践。
注意。为了简洁起见,下面的代码片段只是从数组生成表,但不提供上面描述的附加行为。
(1) 使用指令“template”属性
app.directive('myTableDirective', function() {
return {
restrict: 'E',
replace: true,
scope: {
values: '='
},
template: '<table class="ffrs-table">' +
'<tr>' +
'<th ng-repeat="cell in data.labels">{{cell}}</td>' +
'</tr>' +
'<tr ng-repeat="row in data.values track by $index">' +
'<td class="centered" ng-repeat="cell in row track by $index">{{cell}}</td>' +
'</tr>' +
'</table>',
link: function(scope, elem, attrs)
{
//elem.children() does not return tr/th/td DOM elements
}
};
});
但是这种方法不允许在 link
函数中操作表 DOM 元素,因为它们似乎不存在于该函数中。
(2) jQuery表创建
app.directive('myTableDirective', function() {
return {
restrict: 'E',
replace: false,
scope: {
values: '='
},
link: function(scope, elem, attrs)
{
scope.$watch( 'tableData', function(val)
{
if( val ) {
var row;
for( var t=0; t<val.values.length; t++ ) {
row = angular.element('<tr></tr>');
for( var f=0; f<val.values[t].length; f++ ) {
row.append( '<td>' + val.values[t][f] + '</td>');
}
elem.append( row );
}
}
elem.addClass('my-table-css-class');
}
}
};
});
在此方法中,仍然存在一个问题,因为 addClass
调用似乎适用于该元素,因为它在添加 tr/td 元素之前。
(3) ng-repeat
以及在每个 tr/th/td 元素上使用指令
这是一种我尚未测试过的方法,因为我有 20 多个表格要显示,并且 HTML 文件中的表格代码越短越好...
所以问题是:正确的做法是什么?或者也许它们都不正确,这样的问题应该以其他方式解决?
最佳答案
我相信您的方法#1 走在正确的轨道上。我建议不要尝试在链接函数中完成您需要的操作,而是建议向该指令添加一个 Controller ,其中包含由 ng-click 和 ng-mouseover 触发的函数:
controller: ['$scope', function MyTableController($scope) {
$scope.doSomething = function() {
// your code here
};
$scope.highlightSameValues = function(cell) {
// your code here
};
}];
因此,例如,如果您希望在将鼠标悬停并单击每个单元格时发生某些“事情”,请将您的 td
更改为以下内容:
<td
class="centered"
ng-repeat="cell in row track by $index"
ng-mouseover="doSomething()"
ng-click="highlightSameValues(cell)">
{{cell}}
</td>
关于javascript - 编写 AngularJS 指令以从数组生成表的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39425362/