Thursday, July 31, 2014

AngularJS: manipulate rendered html data after AngularJS has rendered a template

I was working on the table row hover effect for a column span multiple rows ( like this Table Row Hovers with Rowspans, I actually borrowed the rowspan script with some twist )

The script works fine while I was working on ASP.NET MVC; however it started not working while I tried to reuse it for the app in AngularJS.

Why? AngularJS loaded in different time than ASP.NET MVC.... Here is what I figured it out after googling( sure! )

1. create a directive using angularJS $timeout service:
gicGiaApp.directive("ngTopload", ['$timeout', function ($timeout) {
    return {
        link: function ($scope, element, attrs) {
            $scope.$on('myDataloaded', function () {
                $timeout(function () { 

                 //This is the reused function I would like to call
                 //see the definition below 
                 RowSpanHover();  

                }, 0, false);
            })
        }
    };
}]);

2. add directive into the view template
....
<div class="ng-cloak" ng-cloak="" ng-topload="">
....
<table class="tgxxx" id="xxxTOP510"></table>
</div>


3. add this line into the controller to broadcast communicating with $on defined in the directive above:

.....
$scope.$broadcast('myDataloaded');
....



4.And here is the script function being reused both ASP.NET MVC and AngularJS:



function RowSpanHover() {

    $('#xxxResults .tgxxx tbody td').hover(function () {
        $element = $(this);
        $element.parent().prevAll('tr:has(td[colspan]):first').addClass("hover");
        if ($element.parent().has('td[rowspan]').length == 0)
            $element.parent().prevAll('tr:has(td[rowspan]):first').find('td[rowspan]').addClass("hover");
    }, function () {
        $element.parent().prevAll('tr:has(td[rowspan]):first').find('td[rowspan]').removeClass("hover");
    });

}

No comments:

Post a Comment