监视在ng-repeat之外使用的ng-repeat对象



好了,我已经创建了一个ng-repeat来获取由$http.get创建的所有用户。这个get请求通过使用$interval每5秒更新一次,并通过调用$scope.goInfo(data)在单击时显示单个用户数据。这个$scope.goInfo(data)在整个页面中用于显示用户数据,但它是由ng-repeat创建的(但并不总是在ng-repeat中使用)。我怎么能有这个数据对象创建的ng-repeat更新以外的ng-repeat每5秒?我不能在$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-->

检索到新数据后需要重置所选对象。基本上,您只需要在新的对象数组中找到相应的记录,并将其再次设置为selected。

像这样的代码应该可以达到这个效果:

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>

最新更新