【问题标题】:ng-repeat in combination with ng-initng-repeat 与 ng-init 结合使用
【发布时间】:2015-12-05 04:41:59
【问题描述】:

控制器已经在初始化时加载了 $scope.shops。与 defer 和 promise 等异步。我为每个可用的商店创建一个面板。然后我想为每个项目添加列。

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

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

【问题讨论】:

  • 是我自己还是你没有正确地澄清你的问题?
  • 商店面板中列出的项目是相同的,但它们不应该是相同的,因为 ng-init 应该为每个面板加载唯一的项目。但是我现在发现我的工作方式是不可能的,因为我将每个面板的项目绑定到同一个变量。
  • 我将在控制器端进行所有查询。控制器应该返回完整的数据,视图只显示它们。为什么不将 getItemsPershop(shop) 放入控制器中?

标签: angularjs


【解决方案1】:

我会在控制器中制作getItemsPershop()

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

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

【讨论】:

    【解决方案2】:

    按照您的模板的外观,您的作用域中有一个数组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 来初始化作用域上的值。

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

    【讨论】:

    • 接受这个,因为让我想到了结构
    猜你喜欢
    • 2017-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-02
    • 2015-02-09
    • 1970-01-01
    • 1970-01-01
    • 2015-03-04
    相关资源
    最近更新 更多