在Ember中循环控制器

时间:2013-12-08 13:55:57

标签: ember.js

我想知道如何从ember中的ObjectController返回值。我知道ember不允许循环遍历对象控制器,但我需要来自我的控制器的信息才能显示在我的模板中。

这是我想要数据的模板:

 <script type="text/x-handlebars" id="summary"> 
    <table class="table table-bordered table-striped">
        <thead>
            <tr>
                <th>Name</th>
                <th>Total Expenses</th>
                <th>Date</th>
            </tr>
        </thead>
        <tbody>
            {{#each model}}
                <tr>
                    <td>{{name}}</td>
                    <td>{{expense}}</td>
                    <td>{{formattedDate date}}</td>
                </tr>
            {{/each}}
        </tbody>
    </table>
</script>

以下是此模板的控制器:

App.SummaryController = Ember.ObjectController.extend({
    needs: ['expenses'],
    userExpense: function() {
       var userExpenseMap = {}
       var expenses = this.get('controllers.expenses');

       expenses.forEach(function(expense){

           if(userExpenseMap[expense.get('whoPaid')]){
               userExpenseMap[expense.get('whoPaid')] += expense.get('amount');
           }

           else{
               userExpenseMap[expense.get('whoPaid')] = expense.get('amount');   
           }
       });

       userExpenseList = []

       for(var key in userExpenseMap){

           var obj = {};

           obj.name = key;
           obj.expense = userExpenseMap[key];

           userExpenseList.push(obj);
       }

       // console.log(userExpenseList);

       return userExpenseList;
    }.property('controllers.expenses.@each.amount')   
});

1 个答案:

答案 0 :(得分:1)

您可以迭代控制器的任何属性,但它必须是一个数组。因此,您可以在模板中使用{{#each userExpense}}

 <script type="text/x-handlebars" id="summary"> 
    <table class="table table-bordered table-striped">
        <thead>
            <tr>
                <th>Name</th>
                <th>Total Expenses</th>
                <th>Date</th>
            </tr>
        </thead>
        <tbody>
            {{#each userExpense}}
                <tr>
                    <td>{{name}}</td>
                    <td>{{expense}}</td>
                    <td>{{formattedDate date}}</td>
                </tr>
            {{/each}}
        </tbody>
    </table>
</script>