ng-repeat与ng-init结合使用

时间:2015-12-05 04:42:00

标签: angularjs

控制器已经在init上加载了$ scope.shops。与延迟和承诺等异步。我为每个商店创建一个可用的面板。然后我想为每个项目添加列。

我在控制器getItemsPerShop(item)中有一个方法,它也是异步等。我目前得到两个面板(有两个商店),但项目是相同的..可能导致异步问题和$ scope .items没有足够快地下载,我将如何解决这个问题。

   <div ng-repeat="shop in shops">
        <div class="panel panel-default">
            <div class="panel-heading">shop {{shop}}</div>
            <table class="table">
                <thead ng-init="getItemsPershop(shop)">
                    <tr>
                        <th>Number</th>
                        <th>Date</th>
                    </tr>
                </thead>
                <tbody ng-repeat="item in items"> 
                    <tr>
                        <th scope="row">{{item.nr}}</th>
                        <td>{{item.desc}}</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>

这就像一个嵌套的情况,每个面板需要加载它的行。

2 个答案:

答案 0 :(得分:2)

我将继续在控制器中制作getItemsPershop()

您是否忘记了items =中的ng-init

<div ng-repeat="shop in shops">
        <div class="panel panel-default">
            <div class="panel-heading">shop {{shop}}</div>
            <table class="table">
                <!-- forgot "items =" ? -->
                <thead ng-init="items = getItemsPershop(shop)">
                    <tr>
                        <th>Number</th>
                        <th>Date</th>
                    </tr>
                </thead>
                <tbody ng-repeat="item in items"> 
                    <tr>
                        <th scope="row">{{item.nr}}</th>
                        <td>{{item.desc}}</td>
                    </tr>
                </tbody>
            </table>
        </div>
</div>

答案 1 :(得分:1)

模板的外观,您的范围中有一个数组items。但是,您需要将它嵌套在商店中,否则您无法区分它们。

最后看起来像这样:

<tbody ng-repeat="item in shop.items"> 
    <tr>
        <th scope="row">{{item.nr}}</th>
        <td>{{item.desc}}</td>
    </tr>
</tbody>

正如另一个答案中所指出的,您可以将项目分配到当前商店本地范围内的字段items。但是我不鼓励你这样做。来自the docs

  

ngInit只有少数适​​当的用法,例如用于别名ngRepeat的特殊属性,如下面的演示所示;并通过服务器端脚本注入数据。除了这几种情况,您应该使用控制器而不是ngInit来初始化作用域上的值。

在角度中,您应该在控制器中初始化模型并通过模板渲染它。混合这两者会使您的代码更难理解,测试和维护。