Angular Directives如何用于重复数据

时间:2014-12-03 09:46:25

标签: javascript angularjs angularjs-directive

所以我正在做一个webservice调用,返回地址数据,即地址线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>

这样可以正常工作,但看起来不是很有角度,我应该创建一个指令来处理这个可能适用于这两个列表的指令吗?

2 个答案:

答案 0 :(得分:1)

我写了一个快速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'
  };
});

addressList.html:

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

答案 1 :(得分:0)

看看这是否有效。您可以使服务返回一个包含所有地址行的数组,而不是使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>