如何每秒自动更新 ng-repeat 集合中的 html 元素

How to update html element in ng-repeat collection every second automatically

在我的控制器中,我有一个函数,每 2 秒($interval)从 API 接收数据。该数据被呈现并显示给用户。当我从 API 中得到正数时,我想将 HTML 中的背景颜色设置为绿色 1 秒,然后 return 将其设置为原始颜色。如果为负,设置背景色为红色1秒,以此类推...

controller.js

function checkForUpdatedIndices(){
  dataService.getIndices().then(function(res){
    $scope.recentIndeces = res.data;        
 });}

 var indicesTimer = setInterval(checkForUpdatedIndices,2000);
 checkForUpdatedIndices();

我的HTML:

<ul id="ctr_indices">
        <li class="cl_indeces" ng-repeat="i in recentIndeces track by $index">
            <span class="itemname">{{i.itemName}}</span>
            <span class="itemlastvalue">{{i.itemLastValue}}</span>
            <span class="itemchange">{{i.itemChange}}</span>
            <span class="itempercentage">{{i.itemPercentageChange}}</span>
        </li>
 </ul>

当 i.itemLastValue 包含“+”时,我希望它显示为绿色 1 秒,然后再将其变回原始颜色。 提前致谢

您可以使用 ng-style 指令执行此操作。像这样设置样式

ng-style="{'background-color' : i.color}"

并在 ng-init 中调用一个函数并将项目作为参数传递

<span class="itemlastvalue" ng-style="{'background-color' : i.color}" ng-init="setColor(i)">{{i.itemLastValue}}</span>

函数中根据条件赋色,使用timeout函数反转为原值

$scope.setColor = function(i){
    if( i.itemLastValue == "+"){
      i.color = 'green'
    }
    else if( i.itemLastValue == "-"){
      i.color = 'red'
    }

    $timeout(function(){
       i.color = "white" // what ever the original value 
    },1000)
}

已更新

第二种情况是删除ng-init函数并调用checkForUpdatedIndices

中的函数
function checkForUpdatedIndices(){
  dataService.getIndices().then(function(res){
    $scope.recentIndeces = res.data; 
    setColor()       
 });
}

function setColor(){
   var backUp = angular.copy($scope.recentIndeces);
   for(var i=0; i<= $scope.recentIndeces.length-1; i++){
      if( $scope.recentIndeces[i].itemLastValue == "+"){
        $scope.recentIndeces[i].color = 'green'
      }
      else if( $scope.recentIndeces[i].itemLastValue == "-"){
        $scope.recentIndeces[i].color = 'red'
      }
   }
   $timeout(function(){
      $scope.recentIndeces =  angular.copy(backUp);
   },1000)
}