单击ng-repeat内的ng-repeat项目数据

时间:2014-03-09 10:52:07

标签: angularjs angularjs-ng-repeat

我正在使用angularjs框架,我不知道如何在用户点击它(延迟加载)时更新第一个项目ng-repeat中的第二个ng-repeat数据

<table class="table table-striped table-hover">
    <tbody ng-repeat="customer in customers">
        <tr>
            <td>
                <button ng-click="loadInvoices(customer); showDetails = !showDetails;" type="button" class="btn btn-default btn-xs">
            </td>
            <td>{{customer.ClientId}}</td>
        </tr>
        <tr ng-show="showDetails">
            <td>
                <table class="table table-striped table-hover">
                    <tbody ng-repeat="invoice in invoices">
                        <tr>
                            <td>{{invoice.Id}}</td>
                        </tr>
                    </tbody>
                </table>
            </td>
        </tr><!--showDetails-->
    </tbody><!--.customer-->
</table>

我怎样才能实现它?谢谢你的帮助! :)

2 个答案:

答案 0 :(得分:2)

您可以这样做:

<button ng-click="loadInvoices(customer);" type="button" class="btn btn-default btn- xs">Invoces</button>

并在控制器中:

$scope.loadInvoices = function(customer) {
    if (this.showDetails = !this.showDetails) {
        if (!this.invoices) {
            // Load invoices for current customer (probably using service)
            Customer.loadInvoices(customer.ClientId).then(function(invoices) {
                customer.invoices = invoices;
            });
        }
    }
}

通过检查if (!this.invoices) {...}this指向当前客户范围),确保当前客户尚未加载发票,您需要加载它们。在随后的按钮点击customer.invoices将会可用,您将不会再次加载数据。

我还添加了一个示例,说明如何使用Customer服务适合此工作流程。

查看演示:http://plnkr.co/edit/LerBd9ZTPLwhp8JZ6xwU?p=preview

答案 1 :(得分:1)

使用ng-controller指令

只需使用ng-controller指令告知客户范围将由您传入的控制器实例管理。


使用自定义指令

典型的设计:带有客户控制器的客户指令,管理一个客户的范围。

关键是:

  • ng-repeat创建子范围
  • 添加指令以将控制器附加到每个范围
  • 您现在可以独立管理每个客户范围。


控制器,在两种情况下

此控制器将保留loadInvoices,将invoices阵列附加到客户范围。

  

为什么要使用自定义指令?您还可以为客户提供单独的模板,特定的预链接和后链接功能等。

     

为什么客户特定的控制器,因为范围继承将使loadInvoices上下文成为客户特定的范围?可扩展性,可测试性,解耦。

相关问题