好的,我创建了一个ng-repeat来获取$ http.get创建的所有用户。此get请求使用$ interval每5秒更新一次,并在通过调用$ scope.goInfo(data)单击时显示单个用户数据。这个$ scope.goInfo(数据)在整个页面中用于显示用户数据,但是由ng-repeat创建(但并不总是在ng-repeat中使用)。如何在ng-repeat之外每隔5秒更新ng-repeat更新创建的数据对象?我无法在$ interval中包装$ scope.goInfo()。
实施例
//CONTROLLER//
function liveFeed(){
$http.get('some URL').then(function (user) {
$scope.user = user.data;
console.log('user data is', $scope.user);
});
}
//Updates get req every five secs//
$interval(liveFeed, 5000);
//gets data obj from ng-repeat, needs to be updated every 5 secs.//
$scope.goInfo = function (data) {
$scope.name = data.name;
$scope.beats = data.beats;
}
HTML
<table>
<th>First Name: John</th>
<th>Last Name:</th>
<tr ng-repeat="data in user" ng-click = "goInfo(data)">
<td>{{data.name}}<td>
</tr>
</table>
<span>{{beats}}</span><!--needs to update every 5 secs, outside of ng-repeat and be binded to the user that was clicked on-->
答案 0 :(得分:0)
您需要在检索新数据后重置所选对象。基本上,您只需要在新的对象数组中找到相应的记录,并将其再次设置为选中状态。
这样的事情可以解决问题:
function liveFeed() {
$http.get('some URL').then(function(user) {
$scope.user = user.data;
// Find the record that was selected before this update
if ($scope.selectedUser) {
$scope.selectedUser = $scope.user.filter(function(obj) {
return obj.name === $scope.selectedUser.name; // or compare by unique id
})[0];
}
});
}
// Updates get req every five secs
$interval(liveFeed, 5000);
// Gets data obj from ng-repeat, needs to be updated every 5 secs
$scope.goInfo = function(data) {
$scope.selectedUser = data;
}
和HTML将使用selectedUser
:
<table>
<tr>
<th>First Name: John</th>
<th>Beats:</th>
</tr>
<tr ng-repeat="data in user" ng-click="goInfo(data)">
<td>{{data.name}}<td>
<td>{{data.beats}}</td>
</tr>
</table>
<span>{{selectedUser.beats}}</span>