【问题标题】:How can I add HTML to this Knockout.js Viewmodel variable? [duplicate]如何将 HTML 添加到此 Knockout.js Viewmodel 变量? [复制]
【发布时间】:2015-06-16 21:16:46
【问题描述】:

我在页面上显示了一个步骤列表。一些步骤(但不是全部)会有 1-3 个子步骤。我在想最简单的方法是在视图模型的每个步骤声明中手动编写 HTML。

如果你看下面的代码,我想做的是这样的:

this.sidebarStepModel1 = new SidebarStepModel();
this.sidebarStepModel1.message("step 2 <ul><li>substep 1</li><li>substep2</li></ul>");

问题是,写在那里的 HTML 被解释为 string 而不是 HTML。我怎样才能使它将 HTML 解释为实际的 HTML?

小提琴:https://jsfiddle.net/8o31m6rq/2/

HTML:

<ul>
    <sidebar-step params="vm: sidebarStepModel0"></sidebar-step>
    <sidebar-step params="vm: sidebarStepModel1"></sidebar-step>
    <sidebar-step params="vm: sidebarStepModel2"></sidebar-step>
</ul>

JavaScript/淘汰赛:

//custom element <sidebar-step>
ko.components.register("sidebar-step", {
    synchronous: true,
    viewModel: function (params) {
        this.vm = params.vm;
    },

    template: "<li data-bind='text: vm.message'>vm.onChangeElement</li>"
});

// model
var SidebarStepModel = function () {
    this.message = ko.observable("step description");
};

// viewmodel
var OrderGuideViewModel = function () {

    this.sidebarStepModel0 = new SidebarStepModel();
    this.sidebarStepModel0.message("step 1");

    this.sidebarStepModel1 = new SidebarStepModel();
    this.sidebarStepModel1.message("step 2");

    this.sidebarStepModel2 = new SidebarStepModel();
    this.sidebarStepModel2.message("step 3");
};

ko.applyBindings(new OrderGuideViewModel());

【问题讨论】:

    标签: javascript html knockout.js knockout-components knockout-templating


    【解决方案1】:

    您只需要使用html binding 而不是text 绑定:

    template: "<li data-bind='html: vm.message'>vm.onChangeElement</li>"
    

    Updated fiddle

    【讨论】:

    • 嗯,这很简单......我不知道。泰
    猜你喜欢
    • 2012-06-08
    • 2015-10-06
    • 2020-07-23
    • 2019-07-15
    • 2015-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多