繁体   English   中英

ng-repeat与ng-init结合使用

[英]ng-repeat in combination with ng-init

控制器已经在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>

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

我将在控制器中创建getItemsPershop()

你忘记了ng-inititems =吗?

<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>

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

最后它看起来像这样:

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM