0

在我的控制器中,我有一個函數每隔2秒從$ API接收數據($ interval)。這些數據被呈現並顯示給用戶。當我從我的API獲得正數時,我想將HTML中的背景顏色設置爲綠色1秒,然後將其恢復爲原始顏色。如果是負數,設置背景顏色爲紅色1秒,依此類推......如何自動更新ng-repeat集合中的html元素

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秒,然後將其改回原來的顏色。 在此先感謝

回答

0

您可以使用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) 
} 
+0

感謝您迴應的功能。在你的例子中,setColor函數只被調用一次。每次更改i.itemLastValue時,我都需要更新它。 – Vitali

+0

什麼時候改變 –

+0

每2秒。我用setInterval向我的API發送請求。 var indicesTimer = setInterval(checkForUpdatedIndices,2000); checkForUpdatedIndices(); – Vitali