使用范围作为 id 在传单中创建地图

Use scope as id to create map in Leaflet

本文关键字:单中 创建 地图 id 使用范围      更新时间:2023-09-26
鉴于我使用 ng-repeat,

它允许我对每个项目使用 $index,我尝试使用此属性为 ng-repeat 中的每个项目创建一个映射

视图

 <div map-directive id="map{{$index}}" name="'map' + [$index]" class="mapContainers">
 </div>

所以现在 id 是 map0、map1 等等。

命令

    var map = L.map(scope.name, {
                        center: [40.766964, -73.930453],
                        zoom: 4,
                        layers: [BaseMap]
                    });

在指令中 scope.name 包含唯一 id。

我发现地图只有在更改字符串范围后才能工作

    var map = L.map('map', {
                        center: [40.766964, -73.930453],
                        zoom: 4,
                        layers: [BaseMap]
                    });

也许有人已经遇到了类似的问题。

当您可以简单地使用 link 方法提供的指令的 element 属性时,为什么要特意使用 ID?它的存在是有原因的,也可能只是使用它:

angular.module('app', [
  'ui.router'
]);
angular.module('app').config([
  '$stateProvider',
  '$urlRouterProvider',
  function ($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise('/');
    $stateProvider.state('root', {
      'url': '/',
      'controller': ['$scope', function ($scope) {
          $scope.maps = ['a', 'b', 'c', 'd'];
      }],
      'template': '<div map-directive ng-repeat="map in maps" class="map"></div>'
    });
  }
]);
angular.module('app').directive('mapDirective', function () {
  return {
    restrict: 'A',
    link: function (scope, element, attrs) {
      var map = L.map(element[0], {
        center: [0, 0],
        zoom: 1,
        layers: [
          L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', {
            attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, &copy; <a href="http://cartodb.com/attributions">CartoDB</a>',
            maxZoom: 18
          })  
        ]
      });
    }
  };
});

像魅力一样工作:http://plnkr.co/edit/toZByf9QSletY5erXID7?p=preview

我将尝试解释这里实际发生的事情。如果使用模板字符串添加 ID:

<div map-directive ng-repeat="map in maps" id="map_{{$index}}" class="map"></div>

指令link(前或后,无关紧要)函数被执行:

'link': function (scope, element, attrs) {
    console.log(element[0]);
    console.log(attr.id);
}

在这里attrs.id返回ng-repeat中第一个元素的map_0,这很棒。我们有身份证。但是此时element[0](已创建的实际元素)仍返回:div#map_{{$index}}.map 。因此,如果您告诉L.Map使用 map_0 作为元素 ID,尽管该元素已经存在于 DOM 中,但该 ID 尚未解析,因此L.Map抛出一个错误,即它找不到该元素:Map container not found

这样做的方法是使用 element 属性,它包含实际元素的引用,L.Map 也接受它,正如你从它的签名中看到的那样:

L.map( <HTMLElement|String> id, <Map options> options? )

http://leafletjs.com/reference.html#map-l.map

如果你分配对实际元素的引用(既然你已经得到了它,为什么不呢?),它节省了L.Map不必为ID进行DOM查找,所以这更好。如果你需要它用于CSS目的或其他目的,你仍然可以分配ID,它只是在指令中没有用。