2014-04-01 51 views
1

我正在構建像這樣的AngularJS指令。我想創建一個可重用的小部件,可以從Google Analytics中提取數據並創建量表圖表,但我堅持了第一步。Angular指令鏈接函數onload

dashboardApp.directive('organicSearchGauge', function() { 
return { 
    scope: { 
     color: '=' 
    }, 
    restrict: 'AE', 
    replace: true, 
    template: '<div id="xxx"></div>', 
    link: function(scope, elem, attrs) { 
     var clientId; 
     var apiKey = 'xxx' 
     var scopes = 'https://www.googleapis.com/auth/analytics.readonly'; 

     function handleClientLoad() { 
      gapi.client.setApiKey(apiKey); 
      window.setTimeout(checkAuth, 1); 
     } ... 

以下功能auth2.0,使API調用,我應該寫我從GA進入<div id="xxx></div>數據。

在HTML文件中,我有一個<script>這樣的:

<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script> 

,這樣我可以加載GA API庫並啓動handleClientLoad()函數。但該指令不起作用。

我想問題是第一個handleClientLoad(),因爲我插入Document.ElemenyByID().innerHTML來測試這個函數是否工作,事實證明它沒有。所以我猜想<script>標籤中的「onLoad =」完全不起作用?你能幫助我嗎?謝謝。

回答

1

由於Google API看起來是附加在窗口對象上的函數,所以您需要在窗口範圍內創建函數。在你的指令中使用依賴注入來得到$ window對象引用並在窗口對象範圍內創建函數。還使用$ timeout這是處理超時的角度方式。

dashboardApp.directive('organicSearchGauge', ['$window', '$timeout', function($window, $timeout) { 
return { 
    scope: { 
     color: '=' 
    }, 
    restrict: 'AE', 
    replace: true, 
    template: '<div id="xxx"></div>', 
    link: function(scope, elem, attrs) { 
     var clientId; 
     var apiKey = 'xxx' 
     var scopes = 'https://www.googleapis.com/auth/analytics.readonly'; 

     $window.handleClientLoad = function() { 
      gapi.client.setApiKey(apiKey); 
      $timeout(function(){ 
       checkAuth(); 
      }, 1); 
     } 
     ..... 
    } 
    } 

}]); 
+0

非常感謝你!這真的很有幫助! – fuermosi777

+0

我有一些其他功能鏈接到handleClientLoad(),我應該添加$窗口。所有的前綴?謝謝。 – fuermosi777

+0

不需要爲鏈接到handleClientLoad()的函數添加$ window前綴,因爲google API將單獨查找應該在窗口範圍內的handleClientLoad()。如果它幫助你,請隨時將其標記爲正確答案。 –

0

handleClientLoad是一個私人功能。作爲快速修復,請將window.handleClientLoad = handleClientLoad添加到您的鏈接功能中。

+0

謝謝。它激發了我,我通過添加一個'window.onLoad = handleClientLoad()'來解決這個問題。 – fuermosi777

相關問題