2016-03-08 81 views
0

將數據綁定參數傳遞給函數敲除

我想格式化價格並以適當的格式打印它。例如,5000000將顯示爲$ 5,000,000。任何人都可以告訴我該怎麼辦?

<span data-bind="text:Price"></span> 
 

 
<span data-bind="function()"></span>

我可以寫一個將採取價值和格式化的內聯函數?可以將文本的值:Price傳遞給formatfunction()嗎?

formatfunction(label){return '$' + label.value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
約淘汰賽

+0

這GIST可能會有所幫助:https://gist.github.com/jakiestfu/7894971 –

+0

還是這個SO職位:http://stackoverflow.com/questions/21144883/knockout -jquery-currency-format –

+0

另一個很好的:https://theweeklybyte.wordpress.com/2014/04/19/three-useful-knockoutjs-extenders/ –

回答

0

一個聰明的事情是,綁定的代碼片段,這樣你就可以在其中使用表達式。所以,你可以調用一個函數:

<span data-bind="text:formatfunction(Price)"></span> 

只是,作爲一項規則,儘量不要讓表達變得非常複雜。複雜的表達式屬於你的視圖模型。

0

您可以使用下面的示例。

(function() { 
    function refresh(element, valueAccessor) { 
     var val = ko.utils.unwrapObservable(valueAccessor()); 
     var text = '$' + val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); 
     $(element).text(text); 
    } 

    ko.bindingHandlers.priceText = { 
     init: refresh, 
     update: refresh 
    } 
})(); 
<span data-bind="priceText:Price"></span> 

這將讓你的模型從特定的UI乾淨「格式化」 computeds,從而使其更具有可重複使用。此外,您可以將價格觀察值添加到您想要的任何模型,而無需每次都添加計算。

0

function ViewModel() { 
 

 
var self=this; 
 
self.formatfunction=function(label){ 
 
        console.log(label); 
 
        return '$' + label.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); 
 
}; 
 

 
ko.applyBindings(new ViewModel());
<span data-bind="text:$parent.formatfunction(Price)"></span>