In my Angular app, we have a bootstrap carousel (using bootstrap carousel rather than ui bootstrap carousel for some reasons), items structure as follows
<div class="item" analytics-on analytics-event="IMPRESSIONS" analytics-category="{{--}}" analytics-label="{{--}}" ng-repeat="banner in vm.bannerList">
<a ng-href="{{--}}" analytics-on analytics-event="CLICK" analytics-category="{{--}}" analytics-label="{{--}}">
<div class="fill" style="background-image: url({{--}});"></div>
</a>
</div>
The click event working fine. But how to track the IMPRESSIONS. The impression event need to trigger when a carousel item becomes active.
I tried to watch the 'active' class using a custom directive but the watch only worked on load time.
Tried and succeeded,
Following custom directive did the job.
//ng-track-carousel-impressions
angular.module('app').directive('ngTrackCarouselImpressions', ['$analytics',function (analytics) {
return {
restrict: 'A',
link: function (scope, element, attrs, controller) {
// create an observer instance
var observer = new MutationObserver(function (mutations) {
scope.$apply(function () {
if (element.hasClass('active')) {
//console.log(element.attr('analytics-label'));
// emit event track (with category and label properties for GA)
analytics.eventTrack(element.attr('analytics-event'), {
category: element.attr('analytics-category'), label: element.attr('analytics-label')
});
}
});
});
// configuration of the observer:
var config = {
attributes: true
};
// pass in the target node, as well as the observer options
var node = element.get(0);
observer.observe(node, config);
}
}
}]);
Usage
<div class="item" analytics-event="IMPRESSIONS" analytics-category="{{--}}" analytics-label="{{--}}" ng-repeat="banner in vm.bannerList" ng-track-carousel-impressions>
<a ng-href="{{--}}" analytics-on analytics-event="CLICK" analytics-category="{{--}}" analytics-label="{{--}}">
<div class="fill" style="background-image: url({{--}});"></div>
</a>
</div>