Getting the model inside a controller emberjs

大憨熊 提交于 2019-12-24 15:12:50

问题


I need to get the grand total price of all the objects returned from a JSON API.

my idea is to create a controller and set a property on it. Then grab the model loop over each object and add to the predefined property that objects total price. Something like this:

export default Ember.Controller.extend({
    orderTotal: 0,

    getOrderTotal: function(){
        var model = this.get('model');

        model.forEach(function(c){
            var order_total = this.get('orderTotal') * c.total_price;
            this.set('orderTotal', order_total)
        });
    }
});

problem is I can't get the model. How can I access the model inside a controller?


回答1:


The model is probably loaded asynchronously, therefore you will have to use .then(...) to wait for the model being loaded.

this.get('model').then(function(data) { ... create sum using `data` });

Though I would use computed properties to create the sum of something that can potentially change:

allPrices: Ember.computed.mapBy('model', 'price'),
totalPrice: Ember.computed.sum('allPrices')

http://emberjs.jsbin.com/wiwiqulozi/1/



来源:https://stackoverflow.com/questions/30628995/getting-the-model-inside-a-controller-emberjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!