具有动态 ng-repeat 项目名称的可重用指令

Reusable directive with dynamic ng-repeat item name

我创建了可重复使用的指令,类似于下拉菜单,但下拉菜单在模态中打开,效果很好。

我的指令看起来像这样

<p-select items="deptStations" header-text="Select " text="Select departure..." text-icon="ion-chatbubble-working" text-field="City_Name_EN" text-field2="City_Code" value-field="City_Code" ng-model="deptStation.value">
</p-select>
<p-select items="arrStations" header-text="Select " text="Select arrival..." text-icon="ion-chatbubble-working" text-field="D.City_Name_EN" text-field2="D.City_Code" value-field="D.City_Code" ng-model="arrStation.value">
</p-select>

我的指令 html 是

<ion-content>
      <div class="list">
        <label ng-repeat="item in items | filter:search" class="item item-text-wrap" ng-click='validateSingle(item)'>
          {{item[textField]}} {{textField2 !== '' ? " (" + item[textField2] + ")" : ""}}
        </label>
      </div>
</ion-content>

现在我的问题是,当 JSON 为 1 级时,它的工作方式如下

[{City_Name_EN:'Abu Dhabi', City_Code:'AUH' },
 {City_Name_EN:'Alexandria',City_Code:'HBE' }]

但是如果我有 2 级 JSON 则它不会工作

[{D:{City_Code:'AMM',City_Name_EN:'Amman'},
 D:{City_Code:'BKK',City_Name_EN:'Bangkok'}}]

那么如何使这部分动态化{{item[textField]}}

我的笨蛋 http://plnkr.co/edit/GxM78QRwSjTrsX1SCxF7?p=preview

有了你的这种动态表达,最好让指令只考虑作为视图模型提供的特定合同。如果指令消费者具有不同的数据格式,则应该由该组件提供指令所需的契约,它可以将数据映射到指令期望的视图模型。这样你就可以保持干净,这是我的意见。

现在要解决您的问题,您需要做一个技巧来评估对象的多级 属性。您可以使用 $scope.$eval 来根据范围对象评估任何动态表达式。例如,您可以通过执行 $scope.$eval("prop1.prop2.prop3", item)$scope.$eval("item." + "prop1.prop2.prop3")

在范围 属性 item 上评估 prop1.prop2.prop3 的动态 属性 评估

所以在你的指令中:

添加了范围函数以获取项目文本和值:

$scope.getItemName = function(field, item){
   //here "this" represents the current child scope of ng-repeat
   return $scope.$eval(field, item);
   //return this.$eval("item." + field); 
}

 $scope.validateSingle = function(item) {
      $scope.text = $scope.$eval($scope.textField, item) + ($scope.textField2 !== '' ? " (" + $scope.$eval($scope.textField2, item) + ")" : "");
      $scope.value = $scope.$eval($scope.valueField, item);

     ...

更新您的模板以获取相应的文本:

    <label ng-repeat="item in items | filter:search" class="item item-text-wrap" ng-click='validateSingle(item)'>
      {{getItemName(textField, item)}} {{textField2 !== '' ? " (" + getItemName(textField2, item) + ")" : ""}}
    </label>

Plnkr