2016-09-16 24 views
0

My api調用返回html,但如果該html爲空,例如我得到一個控制檯html響應「」,我想用knockout顯示默認消息。所以我猜測它需要認識到「」是空的,然後顯示我的備用內容。
視圖模型 -如果HTML響應爲空,則顯示備用內容

var MyText = ko.observable(); 

    var company = shell.authenticatedCompany(); 
    hazibo.helpTextGet(company.name, company.userName, company.password).then(function (data) { 
     MyText(data); 
    }); 


return { 
    MyText: MyText 

};

視圖 -

<section class="help-text"> 
    <div class="flex-container"> 
     <div class="flex-item" data-bind="html: MyText">This is my alternate message if the html response is ""</div> 
    </div> 
</section> 

回答

0

有幾個方法,你可以去了解它。就我個人而言,我希望儘可能多地保留代碼,以便在api回調中檢查您的響應數據並將其設置在那裏。如果您只是適當地更新觀察值,則無需創建凌亂的數據綁定。

hazibo.helpTextGet(company.name, company.userName, company.password).then(function (data) { 
    if(!data) { 
     MyText("This is my alternate message..."); 
    }else{ 
     MyText(data); 
    } 
}); 

如果您需要保留什麼API調用實際返回的,你可以把邏輯的計算代替,並綁定到。實現這一

0

的一種方式是使用一個計算觀察到的,以確定哪些組HTML來顯示:

https://jsfiddle.net/dw1284/ucnewzwo/

HTML:

<section class="help-text"> 
    <div class="flex-container"> 
    <div class="flex-item" data-bind="html: ItemHtml()"></div> 
    </div> 
</section> 

JavaScript的:

function ViewModel() { 
    var self = this; 

    // Html populated from API call 
    self.MyText = ko.observable(''); 

    // Default Html 
    self.Default = ko.observable('This is my alternate message if the html response is ""'); 

    // Computed observable chooses which HTML to display (bind this to view) 
    self.ItemHtml = ko.computed(function() { 
    if (!self.MyText() || self.MyText() === '') { 
     return self.Default(); 
    } else { 
     return self.MyText(); 
    } 
    }); 
} 

ko.applyBindings(new ViewModel());