Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get first object in ng-repeat

Tags:

angularjs

I am displaying a contact's information using ng-repeat. Each contact has details. I am trying to grab the first object in the list. Here is my code:

<div ng-repeat="contact in contactList() | filter:{type: 'direct'} | filter:{duration: '1 year'} | orderBy: 'Date'">
    <div ng-click="selectedContact(contact)">
        <div>{{contact.name}}</div>
        <div>{{contact.type}}</div>
    </div>
</div>

contactList() is a function calling services:

$scope.contactList = function () {
    return ContactService.getContactList();
};

How do I get the first contact object in the ng-repeat? I want to save that object for other windows.

like image 279
hanu Avatar asked Jan 23 '26 17:01

hanu


1 Answers

I'm guessing you don't just want to display the one record and you also want the first record from the array after your filters/ordering are applied. If that is the case I would recommend simply adding an alias after your last condition and then you can reference that alias in your controller.

here is a fiddle to help show:

http://jsfiddle.net/nbavesuo/

I would suggest you not call the function in the ng-repeat instead reference an array that has already been called:

<div ng-repeat="contact in contactList| 
    filter:{type: 'direct'}| filter:{duration:'1 year'}| 
    orderBy: 'Date' as filteredArray">
....

Then in your controller:

$scope.contactList = ContactService.getContactList();

$scope.selectedContact = function(contact){
    console.log(contact);
    console.log($scope.filteredArray[0]);
}

You'll see that $scope.filteredArray[0] will have the 1st element in the sorted array.

like image 184
Kyle Avatar answered Jan 25 '26 13:01

Kyle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!