AngularJS在函数之外更改变量

时间:2016-10-08 22:40:34

标签: angularjs scope

我在Angular中有一个功能,可以在用户点击地图时更改Google地图的中心值。然后向屏幕提醒正确的中心值,但标记不会像它应该那样改变到该位置。

网页:http://alainwebdesign.ca/pl2/#/getLocation

控制器:

.controller('GetlocationCtrl', ['$scope', "uiGmapLogger", "uiGmapGoogleMapApi", "$state", "$stateParams",
      function ($scope, $log, GoogleMapApi, $state, $stateParams) {
          $log.currentLevel = $log.LEVELS.debug;
          center = { latitude: 49.22, longitude: -122.66 }; //default center
          alert(JSON.stringify(center));

          console.log($stateParams);

          $scope.map = {
              center: center,
              pan: false,
              zoom: 16,
              refresh: false,
              events: 
          { click: function newCenter(mapModel, eventName, originalEventArgs)
              {
                $scope.$apply(function(){
                  var e = originalEventArgs[0];
                  center = { latitude: e.latLng.lat(), longitude: e.latLng.lng() };
                  alert(JSON.stringify(center));
                  return center;
                });
              }
          }

          }

HTML partial / view:

<!--Add ability to input location as address-->

<div style="height: 100%">
    <h1>TEST</h1> <!--NOT SHOWING ON PAGE WHICH MEANS THIS IS NOT BEING INVOKED WHEN
                  URL IS: '/getLocation' like it should-->
        <ui-gmap-google-map
                        center='map.center'
                        zoom='map.zoom'
                        draggable='map.draggable'
                        dragging='map.dragging'
                        refresh='map.refresh'
                        options='map.options'
                        events='map.events'
                        pan='map.pan'>


        <ui-gmap-marker
        idKey='1'
        events='map.events'
        coords='map.center'
        >
       </ui-gmap-marker>

    </ui-gmap-google-map>

<script src='//maps.googleapis.com/maps/api/js?key=AIzaSyD4_0KuPivZyV-1EwNGmBCgLc_Z0o8Dyw8'></script>
</div>

1 个答案:

答案 0 :(得分:0)

您可以直接设置 $ scope.map.center 而不是中心变量,这样就可以了。这是工作点击功能示例:

   click: function newCenter(mapModel, eventName, originalEventArgs)
          {
            $scope.$apply(function(){
              var e = originalEventArgs[0];
              $scope.map.center = { latitude: e.latLng.lat(), longitude: e.latLng.lng() };

            });
          }