角度指令 如何用于重复数据

Angular Directives how to use for repeating data

本文关键字:用于 数据 指令 何用于      更新时间:2023-09-26

所以我正在做一个返回地址数据的网络服务调用,即地址行 1-10 两次。

我的观点看起来像这样:

<div ng-repeat="address in search.result.addresses">
  <strong>{{ address.address.addressLine1}}</strong>
  <strong>{{ address.address.addressLine2}}</strong>
  <strong>{{ address.address.addressLine3}}</strong>
  <strong>{{ address.address.addressLine4}}</strong>
  <strong>{{ address.address.addressLine5}}</strong>
  <strong>{{ address.address.addressLine6}}</strong>
  <strong>{{ address.address.addressLine7}}</strong>
  <strong>{{ address.address.addressLine8}}</strong>
  <strong>{{ address.address.addressLine9}}</strong>
</div>
<div ng-repeat="address in search.result.addresses">
  <strong>{{ address.OtherAddress.addressLine1}}</strong>
  <strong>{{ address.OtherAddress.addressLine2}}</strong>
  <strong>{{ address.OtherAddress.addressLine3}}</strong>
  <strong>{{ address.OtherAddress.addressLine4}}</strong>
  <strong>{{ address.OtherAddress.addressLine5}}</strong>
  <strong>{{ address.OtherAddress.addressLine6}}</strong>
  <strong>{{ address.OtherAddress.addressLine7}}</strong>
  <strong>{{ address.OtherAddress.addressLine8}}</strong>
  <strong>{{ address.OtherAddress.addressLine9}}</strong>
</div>

这工作正常,但似乎不是很有棱角,我应该创建一个指令来处理这个问题,这可能适用于两个列表?

我写了一个快速的Plunkr来演示一个基本指令。

用法:

<div ng-repeat="address in Addresses">
  <address-list address=address.address></address-list>
  <address-list address=address.otherAddress></address-list>
</div>

命令:

app.directive('addressList', function() {
  return {
    restrict: 'E',
    scope: {
      address: '=address'
    },
    templateUrl: 'addressList.html'
  };
});

地址列表.html:

<strong>{{ address.addressLine1}}</strong>
<strong>{{ address.addressLine2}}</strong>

看看这是否有效。你可以让服务返回一个包含所有地址行的数组,而不是 seaparing addressLine1, addressLine2, ...

<div ng-repeat="address in search.result.addresses">
    <div ng-repeat="addressLine in address.address">
       <strong>{{ addressLine }}</strong>
    </div>
</div>
<div ng-repeat="address in search.result.addresses">
    <div ng-repeat="addressLine in address.OtherAddress">
       <strong>{{ addressLine }}</strong>
    </div>
</div>