2016-09-16 80 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());