I have implemented Angularytics in my AngularJS web app and it is functioning properly. However, I am facing an issue where it collects statistics from all three environments (development, test, and production) instead of just the production environment. To rectify this, I want to modify the angularytics.js script to include a condition that will only execute the code if the $rootScope.ENVIRONMENT constant is set to Production.
My attempts at finding solutions have been unsuccessful, so now I am considering editing the angularytics.js script to incorporate this specific condition:
(function () {
angular.module('angularytics', []).provider('Angularytics', function () {
if($rootScope.ENVIRONMENT == 'Production') {
var eventHandlersNames = ['Google'];
// Rest of the script here...
})();
Despite having some knowledge of Angular, I seem to struggle with injecting the $rootScope into this script as I always encounter the error message $rootScope is not defined
.
UPDATE Based on the feedback received, here's an improved approach: One way to conditionally add the script would be within a controller like so:
if ($rootScope.ENVIRONMENT == 'Production') {
var head = document.getElementsByTagName('head')[0];
var js = document.createElement("script");
js.type = "text/javascript";
js.src = "lib/plugins/angularytics-yanpy.js";
head.appendChild(js);
}
The contents of angularytics-yanpy.js are as follows:
// Contents of angularytics-yanpy.js
// This script loads Google Analytics asynchronously
// More script details can go here
In addition, you'll need to load the angularytics script on the homepage:
A properly crafted implementation for the production environment; however, when testing in development, a JavaScript error occurs due to angularytics.js requiring the ga object created in angularytics-yanpy.js, which is not loaded in development mode.
Furthermore, I attempted loading
<script src="lib/plugins/angularytics.js"></script>
dynamically, leading to another error because this script defines an angularytics provider present in the app.js file.
To break the chain of errors, I felt compelled to update the angularytics.js script to retain the provider but only perform actions in the case of the production environment.
If my explanation is unclear, please let me know if you require further clarification.