奥莉莉亚数据表重新编译

3
我一直在探索Aurelia,到目前为止,我喜欢我所看到的。我遇到了一个问题,我不太确定如何解决。在我的当前应用程序中,我使用带有服务器端获取数据的angular和jquery datatables来处理大量结果。Datatables有一个函数,您可以在表中添加新行时调用它(fnRowCallback-http://legacy.datatables.net/ref#fnRowCallback或“createdRow”-https://datatables.net/examples/advanced_init/row_callback.html#)-这非常方便,因为您可以在每行之后重新编译dom(成本很高)。
这使您可以引用当前范围(或viewModel)中存在的函数,其中datatable位于其中。例如:
在我的视图模型中:
export class DataTableTest{

  test(){
   alert('this is a test');
 }

在从数据表提取的返回结果中:
{name:'blah',age:40,actions:"<a click.delegate='test();'>Test</a>"}

我似乎无法弄清楚如何在将元素添加到DOM后重新编译它,不知道有什么办法可以做到这一点吗?

有人有什么想法吗?

更新:这些是我传递给datatables的原始选项:

    var options = {
        "fnRowCallback": function (nRow) {
            $compile($(nRow).contents())(scope);
        }
    };

我注入编译器服务后尝试了以下操作:
        "fnRowCallback": function (nRow) {
               this.compiler.compile($(nRow).contents()).fragment.innerHTML;
        },

但是我总是会得到 Uncaught TypeError: Cannot read property 'compile' of undefined 错误 - 我将代码放在“attached”函数中。如果我在这些选项之外使用console.log(this.compiler),它是可用的。另外,我们不需要将HTML返回给datatables,只需对内容进行编译即可。非常感谢您的所有帮助!


作为一个新手,我自己也没有完整的答案,但我建议“无法读取属性…”消息是由于当它在回调的上下文中时,“this”并不是指向类的事实。在声明选项的行之前添加“var self = this;”,然后在回调函数中使用“self.compiler…”。 - shunty
非常感谢您至少参考和处理它 - 它正在单元格周围放置<!--<view>-->标签,但是即使现在它有一个"au-target-id",该函数仍无法在单击时执行 - 不确定为什么。 - Ben Kilah
抱歉,无法帮助编译 - 我的要求还没有达到那个阶段!接下来去学习对话框... - shunty
1个回答

2
您可以使用编译器服务来编译该元素:
import {inject, ViewCompiler, ViewResources, Container} from 'aurelia-framework';

/**
 * Compiler service
 *
 * compiles an HTML element with aurelia
 */
@inject(ViewCompiler, ViewResources, Container)
export class Compiler {

    viewCompiler: any;
    resources: any;
    container: any;

    constructor(viewCompiler, resources, container) {
        this.viewCompiler = viewCompiler;
        this.resources = resources;
        this.container = container;
    }

    compile(templateOrFragment, ctx = null, viewSlot = null):any {
        if (typeof templateOrFragment === "string") {
            var temp = document.createElement('span');
            temp.innerHTML = templateOrFragment;
            templateOrFragment = temp;
        }

        var view = this.viewCompiler.compile(templateOrFragment, this.resources).create(this.container, ctx);

        return view;
    }
}

我在 Kendo 中使用此函数作为单元格模板回调函数(它允许您返回一个字符串,该字符串将成为单元格内容)。
function(dataItem) {
    var cellctx = { "$item": dataItem, "$parent": ctx };
    return this.compiler.compile(templateString, cellctx).fragment.innerHTML;
}

这个操作发生在Aurelia的bind回调函数中,所以ctx是执行上下文。

我只是将当前数据项用上下文包装起来,并将其别名为$item,以便于操作。

大致如下:

<kendo-grid>
    <kendo-grid-col title="Main Office" field="IsMainOffice">
        <kendo-template><img if.bind="$item.IsMainOffice" src="/content/img/accept.png" /></kendo-template>
    </kendo-grid-col>
</kendo-grid>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接