Garrett Garrett - 5 months ago 18
AngularJS Question

Populating a card from and ng-repeat

I was wondering whats the best way to populate a card I've created by selecting a name from a list that has used an ng-repeat. For example the array the ng-repeat is using contains items like this:

firstname: 'Ryan', secondname: 'Garrett', age: 23
. The ng-repeat only pulls the firstname, I want to be able to click the name and populate the card with the other details. What is the best way to do this? I have created a JSFiddle to help with the solution: http://jsfiddle.net/RkykR/2805/. Thanks in advance!

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;
}

Answer

You can pass the index of repeated items to function called with ng-click, and use that index to assign values from array to scope.

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>

Updated example: http://jsfiddle.net/RkykR/2808/