我创建了可重用指令,例如下拉菜单,但下拉菜单以模式打开,效果很好。
我的指令看起来像这样
<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]}}
我的 friend http://plnkr.co/edit/GxM78QRwSjTrsX1SCxF7?p=preview
最佳答案
对于您的这种动态表达,最好让指令仅考虑作为 View 模型提供的特定契约(Contract)。如果指令使用者具有不同的数据格式,则应该由该组件来提供指令所需的契约,它可以将数据映射到指令期望的 View 模型。这样你就可以保持事情干净,这是我的观点。
现在要解决您的问题,您需要采取一些技巧来评估对象的多级属性。您可以使用$scope.$eval
根据范围对象评估任何动态表达式。例如,您可以通过执行 $scope.$eval("prop1.prop2.prop3 ", item)
或 $scope.$eval("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
关于javascript - 具有动态 ng-repeat 项目名称的可重用指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27996468/