2014-09-22 57 views
0

我使用的是Bindings Computed Property in Ember TextField的答案,但希望稍微擴展它。使用Ember.js綁定文本輸入中的計算屬性

這裏是我的模板:

{{input id="dollars" name="dollars" value=formattedDollars class="form-control"}} 

而且在我的控制器:

formattedDollars: function(key, value) { 
    var model = this.get('model'); 
    if(value) { 
     //This is the setter--make sure the stored value is an integer 
     model.set('dollars', +value.toString().replace(/[^\d]/, "")); 
    } else { 
     //This is the getter--return a formatted value 
     return model.get('dollars').toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); 
    } 
}.property('model.dollars') 

這個作品,如果我設置formattedDollars外的文本字段(如model.incrementProperty('dollars', 10)),但如果我真的中鍵入文本輸入,值不保留格式。

我試過在setter中也返回value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","),但是這也不起作用。我如何做到這一點,以便在dollars輸入字段中輸入數字自動格式化?

回答

1

您必須在兩種情況下返回值 - 獲取或設置計算屬性時。 所以,你的代碼應該是:在這兩種情況下

formattedDollars: function(key, value) { 
 
    var model = this.get('model'); 
 
    if(arguments.length > 1) { 
 
     //This is the setter--make sure the stored value is an integer 
 
     model.set('dollars', +value.toString().replace(/[^\d]/, "")); 
 
    } 
 
    //This is the getter--return a formatted value 
 
    return model.get('dollars').toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); 
 
    
 
}.property('model.dollars')

+0

返回值是不那麼直觀.. – TommyKey 2015-11-27 12:30:04