我在{{input value=(cents-to-dollars model.amountInCents)}}使用一个子表达式。它使用自定义助手将价值从美分转换为美元。我的API返回美分。

但是,在 Controller save操作中,console.log(this.get('model.amountInCents'));返回undefined。我想念什么吗?输入助手中的namevalueBinding

如果删除子表达式。 console.log(this.get('model.amountInCents'));输出正常。

// Routes
import Ember from 'ember';

export default Ember.Route.extend({
  model: function(params) {
    return this.store.find('product', params.product_id);
  }
});

// Controller
export default Ember.Controller.extend({
  actions: {
    save: function() {
      console.log(this.get('model.amountInCents')); // returns undefined
      var _this         = this;
      var dollars       = this.get('model.amountInCents');
      var amountInCents = dollars / 100;

      this.get('model').set('amountInCents', amountInCents);

      this.get('model').save().then(function(product){
        _this.transitionToRoute('admin.products.show', product);
      }, function() {
        // Need this promise, so we can render errors, if any, in the form
      });

      return false;
    },
    cancel: function() {
      this.transitionToRoute('products.show', this.get('model'));
    }
  }
});

// Template
<form {{action "save" on="submit"}}>
  <p>
    <label>Name:
      {{input value=model.name}}
    </label>
  </p>

  <p>
    <label>Amount in cents:
      {{input value=(cents-to-dollars model.amountInCents)}}
    </label>
  </p>

  <input type="submit" value="Save"/>
  <button {{action "cancel"}}>Cancel</button>
</form>

最佳答案

首先,(至少在1.9.1版中)您提出的建议并没有真正起作用(请参阅here-该值显示在输入字段之外)。我认为,真正的问题是您没有绑定(bind)到属性,而是绑定(bind)到从帮助程序返回的字符串(这不是您想要的)。

所以,你可以做什么?

您可以按以下方式设置dollars计算属性:

App.IndexController = Ember.ObjectController.extend({
  dollars: function(key, value){
    if (arguments.length > 1) {
      var dollars = value;
      this.set('amountInCents', parseInt(dollars) * 100);
    }

    return this.get('amountInCents') / 100;
  }.property('model.amountInCents')
});

完整的工作示例here

关于ember.js - 我应该如何获得该输入字段的值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28763043/

10-10 09:53
查看更多