我想使用 Angular Directive(指令)嵌入谷歌地图。指令模板运行一个回调 initMap
,它应该调用作用域 initMap
并创建它,但出现错误:
InvalidValueError: initMap is not a function
如何从指令的 HTML 模板调用指令回调?
显示 map 的父 html 文件:
<my-map></my-map>
指令:
( function( ng, app ) {
'use strict';
app.directive( 'myMap', ['$rootScope', function($rootScope) {
return {
restrict: 'AE',
scope : {},
link: function(scope, element, attr) {
scope.Template = '/directive_html/map.html';
scope.initMap = function() {
var map = new google.maps.Map(document.getElementById('contact-map'), { ...
...
};
},
template: "<div ng-include='Template'></div>"
Map.html(指令模板html)
<div id='contact-map'></div>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
<小时/>
<script>
// This is called
function initMap() {
// call directive scope.initMap()
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>
最佳答案
initMap
需要是一个全局函数。
在继续寻找可能的解决方案之前,我强烈建议使用 angular-google-maps图书馆。
但是,您可以执行以下操作:
- 创建
initMap
作为全局函数 - 有一个
mapLoadedService
,一旦 gmap 初始化,它就会返回一个 promise 解决
initMap
上mapLoadedService
中的 promise
因此,将以下内容添加到您的全局 js 中:
var initMap = function(){
var elem = angular.element(document.querySelector('[ng-app]')); //your app qs
var injector = elem.injector();
var mapLoadedService = injector.get('mapLoadedService');
mapLoadedService.loaded();
};
将以下服务添加到您的 Angular 应用程序:
app.factory( 'mapLoadedService', ['$q', function($q) {
var defer = $q.defer();
this.init = function(){
return defer.promise;
};
this.loaded = function(){
defer.resolve();
};
});
然后在你的指令中:
app.directive( 'myMap', ['$rootScope','mapLoadedService', function($rootScope, mapLoadedService) {
return {
restrict: 'AE',
scope : {},
link: function(scope, element, attr) {
scope.Template = '/directive_html/map.html';
//mapLoadedService returns a promise, that only resolves when google maps lib has loaded and is available globally...
mapLoadedService.init().then(function(){
var map = new google.maps.Map(document.getElementById('contact-map'), { });
});
},
template: "<div ng-include='Template'></div>"
}
});
您还应该在 index.html
或应用程序库中加载 Google map 库。
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
关于javascript - Google Maps API - 对指令进行回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35006689/