我想知道通过从使用ng-repeat的列表中选择名称来填充我创建的卡的最佳方式。例如,ng-repeat正在使用的数组包含如下项:firstname: 'Ryan', secondname: 'Garrett', age: 23
。 ng-repeat仅提取名字,我希望能够点击名称并使用其他详细信息填充卡片。做这个的最好方式是什么?我创建了一个JSFiddle来帮助解决方案:http://jsfiddle.net/RkykR/2805/。提前谢谢!
HTML:
<h3>People:</h3>
<br>
<div ng-app ng-controller="MyCtrl">
<ul>
<li ng-repeat="x in items">{{x.firstname}}</li>
</ul>
</div>
<br>
<div>
Persons name:
<br>Secound name:
<br>Age:
</div>
JS:
var m = [
{firstname: 'Ryan', secondname: 'Garrett', age: 23},
{firstname: 'Bob', secondname: 'Coolio', age: 56},
{firstname: 'Clint', secondname: 'Eastwood', age: 34},
{firstname: 'Scott', secondname: 'Eastwood', age: 45},
{firstname: 'Stan', secondname: 'Lee', age: 59},
];
function MyCtrl($scope) {
$scope.items = m;
}
答案 0 :(得分:2)
您可以将重复项的索引传递给使用ng-click调用的函数,并使用该索引将值从数组赋值到范围。
function MyCtrl($scope) {
$scope.items = m;
$scope.getDetails = function(index) {
$scope.details = $scope.items[index]
}
}
HTML:
<div>
Persons name:{{details.firstname}}
<br>Secound name:{{details.secondname}}
<br>Age:{{details.age}}
</div>
答案 1 :(得分:1)
您可以在控制器中拥有selectedItem
属性。
我们来看看:
<强>控制器强>
$scope.selectedItem;
<强>模板强>
ng-click
用于选择当前对象将控制器selectedItem
绑定到卡
<h3>People:</h3>
<br>
<div ng-app ng-controller="MyCtrl">
<ul>
<li ng-repeat="x in items" ng-click='selectedItem = x'>{{x.firstname}}</li>
</ul>
</div>
<br>
<div>
Persons name: {{selectedItem.firstName}}
<br>Secound name: {{selectedItem.secondname}}
<br>Age: {{selectedItem.age}}
</div>
答案 2 :(得分:0)
您可以将ng-click="fillCard(x)"
添加到<li>
并在范围内创建一个功能,如
$scope.fillCard = function(item) {
$scope.firstname = item.firstname;
$scope.secondname = item.secondname;
}
在html中:
Persons name: {{firstname}}
<br>Secound name: {{secondname}}
答案 3 :(得分:0)
您可以使用var myArray = [1,2,3,4,5,6,7,8,9];
function isOdd(value){
return value % 2;
}
myArray.forEach(function(c, i, a){
if(isOdd(c)){
a.splice(i,1);
}
})
console.log(myArray);
并传递点击的项目
ng-click
然后在控制器中:
<li ng-repeat="x in items" ng-click="itemClicked(x)">{{x.firstname}}</li>
并在UI模板中
$scope.itemClicked = function(item){
$scope.selectedItem = item;
}