【问题标题】:ng-click directive is not calling the entire functionng-click 指令没有调用整个函数
【发布时间】:2016-05-04 13:02:06
【问题描述】:

我正在尝试在 google maps 地图内移动一个标记。我有一个移动它们的功能,它们工作正常。为了测试,我在脚本中调用了它们,它们按预期工作。

但是当我尝试在 ng-click 指令中调用该函数时,该函数被调用但整个代码并未被执行。

<md-button class="md-raised md-primary" ng-click="x()">Click here to move the marker</md-button>

方法:

$scope.x = function ()
      {
        console.log('a');
          $scope.marker = {
          id: 6,
          coords: {latitude:-28.226349,longitude:-52.381581}
          };
      }

在控制台内打印“a”,但标记没有移动到纬度:-28.226349,经度:-52.381581。

如果我这样调用脚本中的函数:

$scope.x = function ()
      {
        console.log('a');
          $scope.marker = {
          id: 6,
          coords: {latitude:-28.226349,longitude:-52.381581}
          };
      }

      $scope.x();

加载页面时,标记位于纬度:-28.226349,经度:-52.381581。

整个 HTML:

<md-button class="md-raised md-primary" ng-click="x()">Click here to move the marker</md-button>
<div id="map" ng-controller="MapCtrl">
<ui-gmap-google-map center='map.center' zoom='map.zoom'  options="map.options">

<ui-gmap-marker coords="marker.coords" options="marker.options" events="marker.events" idkey="6"></ui-gmap-marker>

</ui-gmap-google-map>

【问题讨论】:

  • 你能控制台记录 $scope.marker 以检查坐标值是否正在更新吗?这也可能是数据绑定的问题,坐标值正在更新但正确绑定到屏幕。
  • 我现在已经尝试过了,令人惊讶的是坐标更新了......我现在注意到的另一个令人毛骨悚然的事情是,当我调用它时,'a'(来自 console.log)出现了两次在脚本上,只有一次当我通过 ng-click 调用它时,我不知道这是否相关......两种方式(当我通过 ng-click 和脚本调用函数时)坐标更新。
  • 那么您的问题现在解决了吗?坐标是否正确更新您是否仍然面临绑定问题?
  • 不抱歉。我的问题是marker不动,坐标在更新,不知道为什么,还是不动。
  • 看起来这是一个绑定问题(变量更改未绑定到 HTML)。你能分享更多关于如何在 HTML 中绑定坐标的代码吗?

标签: javascript angularjs google-maps angularjs-scope


【解决方案1】:

看看这个代码笔here

它按预期工作。我认为问题出在您的 idkey 上。使 idkey 动态化并将其绑定到标记对象的 ID。

HTML

<div ng-app="myApp" ng-controller="gMap">
  <md-button class="md-raised md-primary" ng-click="x()">Marker</md-button>
  <ui-gmap-google-map 
    center='map.center' 
    zoom='map.zoom' aria-label="Google map">

    <ui-gmap-marker
      coords="marker.coords" options="marker.options" events="marker.events" idkey="marker.id">
      <ui-gmap-window>
        <div>{{marker.window.title}}</div>
      </ui-gmap-window>
    </ui-gmap-marker>

  </ui-gmap-google-map>
</div>

控制器

myApp.controller("gMap", function($scope) {
  $scope.x = function() {
    console.log('a');
    $scope.marker = {
    id: 6,
    "coords": {
      "latitude": "40.7903",
      "longitude": "-73.9597"
    }
  }
  }
  $scope.marker = {
    id: 6,
    "coords": {
      "latitude": "45.5200",
      "longitude": "-122.6819"
    }
  }
  $scope.map = {
    center: {
      latitude: 39.8282,
      longitude: -98.5795
    },
    zoom: 4
  };
});

【讨论】:

  • 完成,我只是将按钮移动到地图 div 中,它起作用了,谢谢 Pratik!
  • 我用路由提供程序调用控制器,然后再次在 HTML 上调用,这就是它显示 console.log 两次的原因,这就是为什么标记也没有移动,我只是删除了'ng-controller="MapCtrl"' 解决了这个问题。再次感谢您帮助我看到它。
猜你喜欢
  • 1970-01-01
  • 2015-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多