2016-04-15 122 views
1

我正在使用angularjs,並且在更新表格中的某個值時,我想將CSS類添加到特定的單元格中。只使表格中突出顯示的單元格值

  • 我該如何只添加高亮類也只有該單元格?而不是整行......使用角度指令

預期行爲:由於更新了Value2,因此只應突出顯示該單元格。

我plunker:http://plnkr.co/edit/mfglNOpluccUKLTlLdja?p=preview

我的表:

<table border="1" style="width: 320px;" class="table table-striped table-hover table-responsive table-bordered"> 
    <thead style="font-weight: bold;"> 
    <tr> 
     <th ng-repeat="column in columnsTest" ng-if="column.checked" ng-bind="column.id"></th> 
    </tr> 
    </thead> 
    <tbody> 
    <tr ng-repeat="row in rows"> 

     <td ng-repeat="column in columnsTest" ng-if="column.checked"> 
     <span class="glyphicon glyphicon-circle-arrow-right" ng-show="column.id === 'Value1'"></span> 
     <span data-highlighter="row.Updated">{{row[column.id]}}</span> 
     </td> 
    </tr> 
    </tbody> 
</table> 

CSS:

.highlight { 
background-color: lightgreen; 
transition: background 200ms; 
} 

角指令:

app.directive('highlighter', ['$timeout', function ($timeout) { 
return { 
    restrict: 'A', 
    scope: { 
     model: '=highlighter' 
    }, 
    link: function (scope, element) { 
     scope.$watch('model', function(updated) { 
       if (updated) { 


       element.addClass('highlight'); 

       // auto remove after some delay 
       $timeout(function() { 
        element.removeClass('highlight'); 
       }, 1000); 
       } 
     }); 
    } 
}; 
+0

當你說「'row.Updated'得到未定義」時,你是什麼意思?是什麼讓你說,這是怎麼一個問題?你的低調看起來像是在按照它應該的方式工作;期望的行爲是什麼? –

+0

對不起,不清楚。我預期的行爲是隻有一個單元格應該突出顯示,而不是整行 – MrProgram

回答

2

這部分的問題是:

model: '=highlighter' 

因爲

<span data-highlighter="row.Updated"> 

這會給modelrow.Updated的價值,那就是將對所有三列改變的值,因爲這是他們的父定義。

將其更改爲

<span data-highlighter="row[column.id]"> 

然後,它的工作原理。


編輯:刪除了我以前的答案。

+0

我想使用該指令。正如你所看到的,我也在那裏刪除了css類 – MrProgram

+0

問題是行中的所有三個單元格都在查看同一個變量'row.Updated',因此如果一個單元格被更新並設置了該標誌,那麼整個行突出顯示。 @ C14L的推薦是好的:爲什麼不直接看到可以直接改變的價值,而不是看父母的標誌?如果使用'data-highlighter ='row [column.id]「',指令將自動監視列的值以進行更改,並在每次執行時突出顯示該列。沒有必要用更新後的標誌手動觸發它 –

+0

下面是一個工作示例:http://plnkr.co/edit/JL691xJfPqKJ4DaacP0m?p=preview;有一點需要注意的是,我改變了'$ watch'的回調函數,取2個變量,'updated'和'previous',並將'if(updated)'改爲'if(!angular.equals(updated,previous))' 。這將確保該值實際上發生了變化,並防止頁面首次加載時所有單元格閃爍等事件,因爲'$ watch()'總是首次啓動 –

相關問題