// declare a module var myApp = this.angular.module('myApp', []); // declare a controller myApp.controller('TableCtrl', function ($scope) { // maximum number of rows that we are creating $scope.maxRows = 30; $scope.generateData = function () { // a variable to store the random value var ran; // this stores the properties of the array of newly created objects $scope.randomObjects = []; // Randomly assign a value to the newly objects created for (var i = 0; i < $scope.maxRows; i++) { var obj = new Object(); ran = Math.round(Math.random()); if (ran == 0) { obj.sel = false; } else { obj.sel = true; } obj.name = "Row " + i + ", hide this row"; $scope.randomObjects.push(obj); } } // Recreate a new list of objects $scope.refresh = function () { $scope.generateData(); } // Create a list of objects $scope.generateData(); }); // Creates a new behaviour that will be applied to the attribute name 'row-style'. myApp.directive('rowStyle', ['$timeout', function ($timeout) { return { restrict: 'A', link: function (scope, elem, attrs) { // Watch for changes in the randomObjects and execute the actions within the function scope.$watch('randomObjects', function () { $timeout(function () { // Find all the <tr> element in the DOM element var rows = elem.find('tr'); // Store the reference to the <tr> element var rowsObj; var count = 0; // Looping through all the rows for (var i = 0; i < rows.length; i++) { rowsObj = angular.element(rows[i]); // Remove all the classes that's affecting the background color of the rows first rowsObj.removeClass("isOdd"); rowsObj.removeClass("isEven"); // We should be keeping a lookout for rows that are not hidden if (!rowsObj.hasClass('ng-hide')) { // Apply the respective style based on the row count if (count % 2 == 0) { rowsObj.addClass('isOdd'); } else { rowsObj.addClass('isEven'); } count++; } } }) }, true) } } }]);
<!-- stitch this with the module declare in Javascript --> <body ng-app="myApp"> <span>Click on the checkboxes to hide the corresponding rows.</span> <div ng-controller="TableCtrl"> <!-- stitch a new behaviour to this DOM element --> <table row-style width="100%"> <tr ng-repeat="obj in randomObjects" ng-show="obj.sel" class="isOdd"> <td> <input type="checkbox" ng-model="obj.sel" />{{obj.name}}</td> </tr> </table> <button ng-click="refresh();">Generate Data Again</button> </div> </body>
tr.isOdd { background-color: #FFBBBB; } tr.isEven { background-color: #BBFFBB; }