如何在angularjs中更改表中单击的“”元素的颜色?

时间:2015-11-02 10:35:27

标签: javascript html angularjs

有一张桌子。

<table id="example" class="table table-responsive table-striped">
    <thead style="">
        <tr>
            <th>Lead Id</th>
            <th>Name</th>
            <th>Mobile Number</th>
            <th>Email</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="customer in allCustomers track by $index"  >
            <td ng-bind="customer.customerId"></td>
            <td ng-bind="customer.firstName + ' ' + customer.lastName"></td>
            <td ng-bind="customer.phoneMobile=='None'?'':customer.phoneMobile"></td>
            <td ng-bind="customer.email"></td>
        </tr>
    </tbody>
</table>

我想绑定点击“th”,这样当我点击任何“th”时,它就会被高举。

1 个答案:

答案 0 :(得分:2)

如果您只想突出显示它,可以创建一个TH指令:

app.directive('th', function() {
    return  {
        restrict: 'E',
        transclude: true,
        scope: true,
        template: '<span ng-transclude ng-click="highlite = !highlite"></span>',
        link: function(scope, element attr) {
            scope.$watch('highlite', function(val) {
                if (val) {
                    element.addClass('highlite');
                }
                else {
                    element.removeClass('highlite');
                }
            });   
        }
    }
});

&#13;
&#13;
var app = angular.module('app',[]);
app.directive('th', function() {
    return  {
            restrict: 'E',
            transclude: true,
            scope: true,
            template: '<span ng-click="highlite = !highlite" ng-transclude></span>',
            link: function(scope, element, attr) {
                scope.$watch('highlite', function(val) {
                    if (val) {
                        element.addClass('highlite');
                    }
                    else {
                        element.removeClass('highlite');
                    }
                })
            }
            
    };
});

   
&#13;
.highlite {
  background-color: yellow;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app">
  
<table>
    <thead>
        <tr>
            <th>Lead Id</th>
            <th>Name</th>
            <th>Mobile Number</th>
            <th>Email</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>A</td>
            <td>B</td>
            <td>C</td>
            <td>D</td>
        </tr>
    </tbody>
</table>
  
</div>
&#13;
&#13;
&#13;