路由不适用于脚本,除非刷新它

Routing not work with scripts unless refresh it

我写了两个简单的页面,我想从一个页面(比如'/')路由到另一个页面('/map'),里面有一个 Google 地图组件,我把脚本放在新控制器,但是当我路由到第二页时什么也没有出现,除非我刷新它 (window.location.replace('#/map') 或 href = "/map")

//routProvider
app.config(function($routeProvider) {
    $routeProvider

// route for the home page
    .when('/', {
        templateUrl : 'template/main.html',
        controller  : 'MainController'
    })
    .when('/map', {
        templateUrl : 'template/map.html',
        controller  : 'MapController'
    })
});

// MapController
app.controller('MapController', function($scope, ) {
    function initialize() {
        var mapProp = {
            center:new google.maps.LatLng(51.508742,-0.120850),
            zoom:5,
            mapTypeId:google.maps.MapTypeId.ROADMAP
        };
        var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
    }

    google.maps.event.addDomListener(window, 'load', initialize);

});

//Map template
<div>
    <p> this is map</p>
    <div id="googleMap" class="mapcover"></div>
</div>

所以问题又是当切换到“/map”时如何让脚本在不刷新的情况下工作

您只需调用初始化函数

NOTE: What google.maps.event.addDomListener will do it will bind event on page load so when yo refresh it will trigger but if you call your controller using routes then it is not page load so that your event is not calling so to solve problem call function directly

app.controller('MapController', function($scope, ) {
    function initialize() {
        var mapProp = {
            center:new google.maps.LatLng(51.508742,-0.120850),
            zoom:5,
            mapTypeId:google.maps.MapTypeId.ROADMAP
        };
        var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
    }
    initialize();
    google.maps.event.addDomListener(window, 'load', initialize);

});