I've configured a constant on a module like below(simplified version of my actual scenario):
var app = angular.module('app', []);
angular.config('AnalyticsConstant', function(){
property: {
click: 'clicked',
swipe: 'swiped',
externalLink: 'opened external link'
},
page: {
message: {
list: 'Message listing',
show: 'Message show'
}
}
}
Now I based on user action taken (say swipe), I want to trigger an analytics event. Since swipe/click or recognizing if an element has an external link, is something done on view level, I want to pass a hash to my controller method.
for example:
<ion-list>
<ion-item ng-repeat="message in messages track by $index" ui-sref="message_path({id: message.id})" class="item-text-wrap">
<my-track-directive source='message', property='click'>
</ion-item>
</ion-list>
Here certainly in myTrackDirective, I can read these two values and check if source/property key is available in AnalyticsConstant. Once found out, I'll also have to check if the value are key another key in AnalyticsConstant.source/property hash. Another pain will be, I'll need to stringify the keys source/property so that I can check in hash, however that's not a problem.
I was wondering if I can access the AnalyticsConstant in view, so that the directive line becomes something like:
<my-track-directive source='AnalyticsConstant[page][message][list]', userAction='AnalyticsConstant[property][click]'>
I could think of three solutions:
- Add inject it root scope. ie.
app.run(function($rootScope, AnalyticsConstant){
$rootScope.analyticsConstant = AnalyticsConstant
}
But this is not a good solution, as if by mistake anyone changes $rootScope.analyticsConstant
to something else, whole functionality may get screwed.
- Inject in each controller and set it at $scope level.
$scope.analyticsConstant = AnalyticsConstant
This will be a lot of duplication. Also, it'll also not ensure if $scope.analyticsConstant
won't get corrupted by mistake.(Though disaster will also be scoped and limited :) )
- Write a function which returns AnalyticsConstant inside 'module.run' or may be inside each controller.
function getAnalyticsConstant = function(){
return AnalyticsConstant
}
I particularly liked the third approach. But question remains where to place this (rootScope or controller-scope)?
My questions are:
- Is there any better way to access configured constant inside view in angular?
- What might be other problems with each of these approach I listed above?
- Is the directive approach is better or should I collect this data in some model and then pass it to analytics event function ?
Thanks