AngularJS 无法加载 Bing 地图

AngularJS fails to load Bing Maps

我正在使用 AngularJS 显示 Bing 地图,但错误显示 "TypeError: Cannot read property 'prototype' of null"。请往下看。

在我的 Razor 视图文件中有以下内容:

<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
<script type="text/javascript" src="~/lib/angular/angular.min.js"></script>
<script src="~/js/Site.js"></script>
----
----
--
<div ng-app="myDisplayItems">
    <div ng-controller="myDisplayItemsController">
        <div id="myMap"></div>
    </div>
</div>

在我的 JavaScript 文件中有:

var displayItems = angular.module("myDisplayItems", []);
displayItems.controller("myDisplayItemsController", function myDisplayItemsController($scope) {
    showMap();
});

function showMap() {         
    var key = "######";

    var map = new Microsoft.Maps.Map('#myMap', {
        credentials: key,
        zoom: 3
    });
}

更新:

var displayItems = angular.module("myDisplayItems", []);
displayItems.controller("myDisplayItemsController", function myDisplayItemsController($scope) {
   $scope.map = null;
   $scope.init = function () {
         $scope.map = showMap();
   };

   angular.element(document).ready(function () {
         $scope.init();
   });
});

显然发生此错误是因为 Bing 地图库在地图初始化后 尚未准备就绪

没有错误发生,是 showMap 函数在一些延迟后被调用(假设 Bing 地图库在那一刻已经加载),例如这样的:

$timeout(function() { $scope.initMap()}, 2000); 

但我会提出以下解决方案:

注册需要触发一次的函数Bing地图库就绪,像这样:

Microsoft.Maps.CallbackOnLoad = "initMap";

并声明initMap一个全局函数:

$window.showMap = function () {
   //...
}

演示

angular.module('mapApp', []);
    angular
        .module('mapApp')
        .controller('MapController', MapController);

    function MapController($scope, $window) {

        $window.initMap = function () {
            let map = new window.Microsoft.Maps.Map(
                document.getElementById('myMap'), {
                    credentials: 'AjwUEXFZA8SMyy8CaJj59vJKVDoWohNXVFz_uGyHlT8N40Jgr-zrhvcxbTNRyDqn'
                });
            map.setView({
                zoom: 6,
                center: new Microsoft.Maps.Location(52.406978607177734, -1.5077600479125977)
            });
        }

        Microsoft.Maps.CallbackOnLoad = "initMap";
    }
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<div ng-app="mapApp" ng-controller="MapController">
    <div id="myMap" style="width:600px;height:400px;"></div>
</div>