2015-11-13 39 views
3

我正在使用ng-repeat显示联系人的信息。每个联系人都有细节。我试图抓住列表中的第一个对象。这里是我的代码:如何获得ng-repeat中的第一个对象

<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()是一个函数调用的服务:

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

我如何获得第一接触物体在NG-重复?我想为其他窗口保存该对象。

+0

可能重复[Angular Js:如何在ng-repeat中查找第一个和最后一个元素并向它们添加特殊类?](http://stackoverflow.com/questions/24973117/angular-js-how-to-查找首先和最后元素in-ng-repeat-and-add-special-cla) – Shomz

回答

1

你可以使用“由$索引道”和“如果NG-”使用,以确定当它的第一个对象:

<div ng-repeat="contact in contactList()| filter:{type: 'direct'}| filter:{duration:'1 year'| orderBy: 'Date' | track by $index" 
    ng-if="$index == 0" 
    ng-init="someMethod()"> 
    <div ng-click="selectedContact(contact)"> 
      <div> {{contact.name}}</div> 
      <div>{{contact.type}}</div> 
    </div> 
</div> 

然后,您可以有一个函数“的someMethod()”在你的控制器该保存对象到窗口对象或本地存储:

function someMethod(key, object) { 
    window.localStorage.setItem(key, object); 
} 

我写了一个对象,如果你想用它来在实际上这个确切的事情使用:

var LocalStorageManager = { 
setValue: function(key, value) { 
    window.localStorage.setItem(key, JSON.stringify(value)); 
}, 
getValue: function(key) { 
    try { 
     return JSON.parse(window.localStorage.getItem(key)); 
    } catch (e) { 

    } 
    } 
}; 

所以,你要和你这样的东西,用它在你的“的someMethod()”:

function someMethod(key, object) { 
    LocalStorageManager.setValue(key, object); 
} 

然后,获取对象,你只想使用“的getValue”方法调用“键'你给这个东西。

+0

您可能还想看看跟踪第一次迭代的'track by $ first'。尽管如此,我还没有使用过。 –

+0

当应用$ index和order by filter应用时,会抛出错误**'错误:[filter:notarray]预期的数组,但接收到:{} ** –

1

您可以将新的作用域属性设置为过滤和排序的结果。注意,你怎么组过滤器与()

<div ng-repeat="contact in contacts = (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> 

然后得到这个列表的第一个它仅仅是[0]

{{ contacts[0] }} 
1

我猜你不只是要显示的一条记录,并且您还希望在之后应用您的过滤器/排序后,从阵列开始的第一条记录。如果是这种情况,我会建议在最后一个条件后添加一个别名,然后在控制器中引用该别名。

这里是一个小提琴,以帮助显示:

http://jsfiddle.net/nbavesuo/

我建议你不叫在NG-重复的功能,而不是引用已经被称为数组:

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

然后在你的控制器中:

$scope.contactList = ContactService.getContactList(); 

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

你会即美元的scope.filteredArray [0]将有排序的数组中的第一个元素。

相关问题