如何在data-bind标签内使用if条件来包含attr标签

时间:2017-01-23 06:30:35

标签: asp.net-mvc-4 knockout.js knockout-mvc

data-bind="text: slottext() , attr : {title: Label}"

如果label为null,那么我不想在此显示attr标记include。

1 个答案:

答案 0 :(得分:2)

Knockout为你做这件事。当您将Label设置为null时,它不会盲目地将title: "null"添加到您的元素中,它实际上会删除该属性。

您可以在源代码中看到此行为:

// To cover cases like "attr: { checked:someProp }", we want to remove the attribute entirely
// when someProp is a "no value"-like value (strictly null, false, or undefined)
// (because the absence of the "checked" attr is how to mark an element as not checked, etc.)

var toRemove = (attrValue === false) || (attrValue === null) || (attrValue === undefined);
if (toRemove)
  element.removeAttribute(attrName);

source

所以,反过来说,如果您希望nullfalse放入data-属性,请务必致电{{1关于价值。

这个代码在一个例子中起作用:



JSON.stringify

var vm = {
  text: "Text",
  label: ko.observable("label")
};


ko.applyBindings(vm);

var wrapper = document.querySelector(".wrapper");

console.log("With label:");
console.log(wrapper.innerHTML);

console.log("Without label:");
vm.label(null);
console.log(wrapper.innerHTML);