mgonto / angularytics

The solution to tracking page views and events in a SPA with AngularJS
MIT License
630 stars 70 forks source link

Multiple directives asking for new/isolated scope #32

Closed jantimon closed 10 years ago

jantimon commented 10 years ago

We are using component directives for example a custom select form element. Obviously these directives require a custom scope to interact with their templates. Unfortunately this causes troubles when using the analytics directive:

Error: Multiple directives [funkySpecialSelectElement, analyticsOn] asking for new/isolated scope.

Why does the analyticsOn require an isolated scope? I would suggest to use var analytics = {}; instead of $scope.$analytics = {}; inside your directive.

What do you think?

      return {
        restrict: 'A',
        link: function ($scope, $element, $attrs) {
          var eventType = $attrs.analyticsOn || inferEventType($element[0]);

          var analytics = {};

          angular.forEach($attrs.$attr, function (attr, name) {
            if (isProperty(name)) {
              analytics[propertyName(name)] = $attrs[name];
              $attrs.$observe(name, function (value) {
                analytics[propertyName(name)] = value;
              });
            }
          });

          angular.element($element[0]).bind(eventType, function ($event) {
            var eventName = $attrs.analyticsEvent || inferEventName($element[0]);
            analytics.eventType = $event.type;

            if ($attrs.analyticsIf) {
              if (!$scope.$eval($attrs.analyticsIf)) {
                return; // Cancel this event if we don't pass the analytics-if condition
              }
            }
            // Allow components to pass through an expression that gets merged on to the event properties
            // eg. analytics-properites='myComponentScope.someConfigExpression.$analyticsProperties'
            if ($attrs.analyticsProperties) {
              angular.extend(analytics, $scope.$eval($attrs.analyticsProperties));
            }
            $analytics.eventTrack(eventName, analytics);
          });
        }
      };
jantimon commented 10 years ago

Mixed this up with the angularitics repo