我正在构建一个像这样的 AngularJS 指令。我想制作一个可重用的小部件,可以从 Google Analytics 中提取数据并创建仪表图表,但我陷入了第一步。
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=”标签根本不起作用?你能帮我解决这个问题吗?谢谢。
最佳答案
当 Google API 查找附加到窗口对象的函数时,您需要在窗口范围内创建该函数。在指令中使用依赖项注入(inject)来获取 $window 对象引用并在 window 对象范围内创建函数。还可以使用 $timeout 这是处理超时的 Angular 方式。
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);
}
.....
}
}
}]);
关于javascript - Angular 指令链接函数 onload,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22794544/