在 AngularJs 表达式中使用 ng-repeat 的 $index 变量
Use ng-repeat's $index variable within an AngularJs expression
我有一个 ng-repeat
div,我需要使用 $index
变量来构建表达式。考虑以下因素:
<div ng-repeat="item in myItems track by $index">
This will throw an error: {{myItemId_{{$index}}.someProperty}}
</div>
如果我有一个名为 "myItemId_0" 的 $scope
变量,我该如何在花括号 {{}} 表达式中使用 $index?我试过省略 $index 变量的大括号,但这也不起作用:
{{myItemId_$index.someProperty}}
因为它是范围内的变量,所以创建一个函数来通过括号表示法检索您的 属性。
HTML:
{{getByIndex($index, "someProperty")}}
控制器:
$scope.getByIndex = function(index, someProperty) {
var propertyName = "myItemId_" + index;
return $scope[propertyName][someProperty];
}
但是,合乎逻辑的解决方案是完全不以这种方式访问您的属性,而是使用您的 ng-repeat.
中已经可用的项目
HTML:
div ng-repeat="item in betterItems track by $index">
{{item.someProperty}}
</div>
控制器:
$scope.betterItems = [];
angular.forEach(myItems, function (i) {
$scope.betterItems.push(createMappedItem(i));
}
即使您必须将 collection 映射到新的 collection(或在需要时重复使用),您仍然可以访问原始项目。它更清洁,更易于维护。此外,如果您开始改变 collection.
,按索引检索可能会非常危险
我有一个 ng-repeat
div,我需要使用 $index
变量来构建表达式。考虑以下因素:
<div ng-repeat="item in myItems track by $index">
This will throw an error: {{myItemId_{{$index}}.someProperty}}
</div>
如果我有一个名为 "myItemId_0" 的 $scope
变量,我该如何在花括号 {{}} 表达式中使用 $index?我试过省略 $index 变量的大括号,但这也不起作用:
{{myItemId_$index.someProperty}}
因为它是范围内的变量,所以创建一个函数来通过括号表示法检索您的 属性。
HTML:
{{getByIndex($index, "someProperty")}}
控制器:
$scope.getByIndex = function(index, someProperty) {
var propertyName = "myItemId_" + index;
return $scope[propertyName][someProperty];
}
但是,合乎逻辑的解决方案是完全不以这种方式访问您的属性,而是使用您的 ng-repeat.
中已经可用的项目HTML:
div ng-repeat="item in betterItems track by $index">
{{item.someProperty}}
</div>
控制器:
$scope.betterItems = [];
angular.forEach(myItems, function (i) {
$scope.betterItems.push(createMappedItem(i));
}
即使您必须将 collection 映射到新的 collection(或在需要时重复使用),您仍然可以访问原始项目。它更清洁,更易于维护。此外,如果您开始改变 collection.
,按索引检索可能会非常危险