这里我有一个handsontable在一个非AngularJS应用程序中工作,我正在开发一个广泛使用AngularJS的新版本(SPA)。
我会知道:是否有一种方法可以将现有的handsontable实现包装在AngularJS指令中,而无需重写一切?
提前感谢!
var hot = new Handsontable(container, {
colHeaders: configTable.columnsHeader,
columns: configTable.columnsConfig,
colWidths: configTable.colWidths,
rowHeight: 5,
data: configTable.data,
minSpareRows: 0,
rowHeaders: false,
contextMenu: false,
currentRowClassName: 'row_selected',
height: parentWindowHeight,
width: parentWindowWidth,
multiSelect: false,
autoWrapRow: true,
autoWrapCol: true,
fillHandle: false,
afterOnCellMouseOver: function (event, coords, cell) {
// Long Implementation...
},
afterOnCellMouseDown: function (r, p, r2, p2) { //(r: Number, p: Number, r2: Number, p2: Number)
// Long Implementation...
},
beforeKeyDown: function (event) { // event: Object
},
beforeChange: function (changes, source) { //(changes: Array, source: String)
// Long Implementation...
},
afterChange: function (changes, source) { // (changes: Array, source: String)
// Long Implementation...
},
beforeValidate: function (value, row, prop, source) { // value: Mixed, row: Number, prop: String, source: String
valorMaximo = numeral($(hot.getColHeader()[prop]).data('valor')).value();
},
cells: function (row, col, prop) {
var cellProperties = {};
var sit = $(this.instance.getData()[row][0])[0];
if (sit !== undefined) {
sit = sit.value;
if (sit != "1" && sit != "+" && sit != "-" && sit != "*") {
cellProperties.readOnly = true;
cellProperties.renderer = disabledRowRenderer;
}
}
return cellProperties;
},
onSelection: function (r, c, r2, c2) { // readOnly cannot be selected
var sit = $(this.getData()[r][0])[0];
var meta = this.getCellMeta(r, c);
if (sit !== undefined) {
sit = sit.value;
if (sit != "1" && sit != "+" && sit != "-" && sit != "*") {
this.deselectCell();
}
}
if (meta.readOnly) {
this.deselectCell();
}
}
});
当然可以。最简单的方法是创建一个简单的指令,将所有现有的逻辑放入链接函数中。您可能需要稍微调整一下代码,以便获得对正在处理的元素的正确引用。看到:
myApp.directive('handsOnTable', function(){
return {
link: function(scope, element){
// Your code here, using the element attribute.
}
};
});
但是…既然你正在切换到AngularJS,我强烈建议重写你的代码。它可能没有那么难,也不需要那么多的工作。它将为您提供更多面向未来的代码,并且您可能可以摆脱jQuery(实际上您应该这样做)。在你的情况下,这可能意味着像autoWrapRow和autoWrapCol这样的大多数选项将成为你指令的属性,而像beforeValidate这样的方法将在控制器中结束。比如:
myApp.directive('handsOnTable', function(){
return {
scope: {
autoWrapRow: '=',
autoWrapCol: '='
},
controller: function($element){
var vm = this;
vm.beforeValidate = beforeValidate;
function beforeValidate(){
// Do stuff. You can use the $element to do DOM manupulation
// but you should keep that to a minimum and try to think the
// Angular way of doing things.
}
},
controllerAs: 'table',
bindToController: true
};
});
希望这对你有帮助。当然,这在很大程度上取决于你对Angular的熟练程度。
你试过不需要jQuery的nhandsontable库吗?
https://github.com/handsontable/ngHandsontable?