0

我已经构建了一项服务,以提供向谷歌地图实例添加标记的可能性,但这仅在我使用 ngRoute 服务在特定控制器内时发生。问题是,当我第一次加载应用程序时,我的服务在注入它的控制器之外不起作用,当我切换到注入它的控制器并且它工作时,但是当我回到它所在的控制器时' t 注入了我的服务!这里的问题在哪里?

ngRoute 配置

var climbingApp = angular.module('climbingApp', ['ngRoute'], 
 function($routeProvider){
    $routeProvider.when('/', {
        controller: 'Main'
    });

    $routeProvider.when ('/newSector', {
        templateUrl: 'app/templates/newSector.html',
        controller: 'addSector'
    });
});

控制器

    function addSector($scope, Markers) {

        Markers.addListener( function ( e ){
                $scope.lat = e.latLng.lat();
            $scope.lng = e.latLng.lng();
        });

    }

    function Main ($scope) {
           $scope.initLocation = {
                   lat: -54.798112,
                   lng: -68.303375
           };

    }

服务

climbingApp.factory('Markers', function($rootScope){
    return {
        addListener: function( callback ) {
            google.maps.event.addListener(
                map,
                'click',
                 function( e ) {
                    var marker = new google.maps.Marker({
                        position: e.latLng,
                        map: map
                    });

                    $rootScope.$apply( function(){ callback( e ); });
                }
            );
        }
    }
});

我想问题是监听器仍然连接到地图实例,但我怎么能破坏它呢?

4

1 回答 1

0

You're going to have to be more specific but make sure your controller is actually being destroyed also make sure you should be using a factory here... I don't find many uses for them as they aren't singletons which means a new instance of your factory is injected into every single controller i.e. if your factory houses data and you inject it into two different controllers the data would be different for both of them. A service on the other hand is a singleton and has the opposite effect. That may be what you're seeing.

于 2013-09-26T07:37:29.283 回答