$ window.ga在AngularJS事件中是未定义的?

时间:2015-04-10 11:03:59

标签: javascript angularjs google-analytics

我正在尝试将 Google Analytics 添加到我的网络SPA应用中。我已将GA脚本添加到index.html文件中:

<script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
        m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

    ga('create', 'UA-XXXXXXXX-1', 'auto');
</script>

这是我的"$stateChangeSuccess"事件:

$rootScope.$on("$stateChangeSuccess", function(event, toState, toParams, fromState, fromParams){
    var url = API_URL+$location.url()
    console.log(url)
    $window.ga('send', 'pageview', { page: url }); // line 54
});

这是我得到的:

>>http://localhost:3030/search
>>angular.js:9959 TypeError: undefined is not a function
    at app.run.js:54
    at Scope.$get.Scope.$broadcast (angular.js:12874)
    at $state.transitionTo.$state.transition.resolved.then.$state.transition (angular-ui-router.js:3218)
    at deferred.promise.then.wrappedCallback (angular.js:11485)
    at angular.js:11571
    at Scope.$get.Scope.$eval (angular.js:12595)
    at Scope.$get.Scope.$digest (angular.js:12407)
    at Scope.$get.Scope.$apply (angular.js:12699)
    at done (angular.js:8287)
    at completeRequest (angular.js:8499)

从这个错误中我可以得到$window.ga()undefined

我做错了什么以及如何让它发挥作用?

1 个答案:

答案 0 :(得分:0)

你确定var url = API_URL+$location.url()这条线路运行良好吗?

您初始化API_URL

的位置

以及您初始化$location的位置?

因此,API_URL$location可能会收到该错误。(但不确定)

因此,您需要声明API_URL值并在$scope.$on事件中注入该位置。

您的代码应为

 $rootScope.$on("$stateChangeSuccess", function($location){
      var API_URL ="Your Url";//Put your url
        var url = API_URL + $location.url();
        console.log(url);
        $window.ga('send', 'pageview', { page: url }); // line 54
    });

修改

尝试以下代码

您错过了初始化$ window

 $rootScope.$on("$stateChangeSuccess", function($location, $window){
            var API_URL = "Your Url"; // Put your url
            var url = API_URL + $location.url();
            console.log(url);
            $window.ga('send', 'pageview', { page: url }); // line 54
        });