2016-09-16 4 views
0

私のapi呼び出しはhtmlを返しますが、htmlが空の場合などです。コンソールのhtmlレスポンスを取得し、ノックアウトを使用してデフォルトのメッセージを表示したい。だから私はそれが ""空であることを認識し、次に私の代替コンテンツを表示する必要があると推測しています。
ビューモデル -HTML応答がnullの場合、代替コンテンツを表示します

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コールバックであなたの応答データをチェックしてそこに設定するのが好きです。 Observableを適切に更新するだけで、面倒なデータバインディングを作成する必要はありません。

実際に返されたAPI呼び出しを保持する必要がある場合は、代わりに計算されたロジックにロジックを配置してバインドすることができます。

0

これを達成する1つの方法は、ディスプレイに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()); 
関連する問題