我需要在ng-click上从ng-repeat中获取当前对象,我不能使用$index,因为我使用的是orderBy,因此它给了我相对于范围对象的错误索引。理想情况下,我希望能够点击对象(缩略图),并有$scope。activePerson获得所有对象的值。
数据结构如下:
[
{
'name': 'john'
},
{
'name': 'toby'
},
{
'name': 'sarah'
}
]
这是非常简化的,我的真实对象有30+ KV对和子对象。有10个对象我正在重复(每批4个)。
我当前的HTML是:
.item.fourth(ng-repeat="person in people | orderBy:'-name' " ng-show="$index <= 3" nid="{{person.guid}}"
谢谢
ng-repeat="person in people"
中只有person
;
我不知道你在用什么标记,你肯定没有html,但你想要这样的:
<div
ng-repeat="person in people | orderBy:'-name' "
ng-show="$index <= 3"
nid="{{person.guid}}"
ng-click="activePerson = person">
</div>
注意ng-repeat创建了一个子作用域,因此您需要在父作用域中已经设置了activePerson
。
您可以使用orderBy并从ng-repeat复制当前对象,参见此plunkr。相关代码:
控制器var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.stuff = [
{
'name': 'john'
},
{
'name': 'toby'
},
{
'name': 'sarah'
}
];
$scope.setActivePerson = function (obj) {
$scope.activePerson = obj;
};
});
<<p> 视图/strong> <body ng-controller="MainCtrl">
<div ng-repeat="thing in stuff | orderBy: 'name'">
<input type="radio" ng-click="setActivePerson(thing)" />
{{ thing.name }}
</div>
<br />
<div ng-model="activePerson">Active: {{ activePerson.name }}</div>
</body>