2016-04-15 126 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()'总是首次启动 –

相关问题