这里我有一个在非 AngularJS 应用程序中工作的 Handsontable,并且我正在开发广泛使用 AngularJS (SPA) 的软件的新版本。
我想知道:有没有一种方法可以将现有的可手动实现包装在 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,我强烈建议您重写代码。这可能没那么难,也没有那么多工作。它将为您提供更多面向 future 的代码,并且您可能可以摆脱 jQuery(实际上您应该这样做)。在您的情况下,这可能意味着大多数选项(如 autoWrapRow 和 autoWrapCol)将成为指令的属性,而方法(如 beforeValidate)将最终出现在 Controller 中。像这样的东西:
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 的掌握程度。
关于javascript - 如何在指令 AngularJS 中包装 jQuery(默认)handsontable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32829426/