Search code examples
asp.net-mvc-4knockout.jsknockout-mvc

how to use if condition inside data-bind tag to include attr tag


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

If label is null then i don't want to show attr tag include in this.


Solution

  • Knockout does this for you. When you set Label to null, it doesn't blindly add title: "null" to your element, it actually removes the attribute.

    You can see this behaviour in the source code:

    // 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

    So, the other way around, if you ever want to put null or false in a data- attribute, make sure to call JSON.stringify on the value.

    This code in action in an example:

    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);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
    
    <div class="wrapper">
      <div data-bind="text: text, attr: { title: label }"></div>
    </div>