【问题标题】:How to initialize a leaflet map using formly custom template?如何使用正式的自定义模板初始化传单地图?
【发布时间】:2016-07-07 19:19:40
【问题描述】:

我正在使用 Angular-Formly 创建一个表单,您可以在其中输入地址并从该本地返回地图。我使用以下内容创建了一个自定义模板:

<script type="text/ng-template" id="leaflet-map-template.html"> <div id="[options.key]"></div> </script>

并将类型设置为angular.module 与其他模块:

var app = angular.module('formlyExample', [
    'ngAnimate',
    'ngSanitize',
    'ngTouch',
    'formly',
    'formlyBootstrap',
    'ui.bootstrap'
  ], function config(formlyConfigProvider) {
    // set custom template here
    formlyConfigProvider.setType({
      name: 'leaflet-map',
      templateUrl: 'leaflet-map-template.html'
    });
  });

但在现场我不知道如何初始化传单地图。这是我的字段数组的一部分:

vm.formFields = [
//other fields come here
//leaflet map template
{
  key: 'mymap',
  type: 'leaflet-map',
  templateOptions: {
  label: 'Leaflet Map'
  },
  controller: /* @ngInject */ function($scope) {
    var initialCoordinates = [-23.0895164, -47.2187371];
    // initialize map with initial coordinates
    var map = L.map($scope.options.key, {
      center: initialCoordinates,
      zoom: 14,
      zoomControl: false
    });
  }
}];

--编辑-- 它给我的错误是:Map container not found,因为它找不到div

【问题讨论】:

    标签: javascript angularjs leaflet angular-formly


    【解决方案1】:

    这不起作用,因为控制器将在 DOM 中没有具有正确 ID 的元素时被调用,因为 Formly 尚未应用模板。

    那么...如何解决它?首先,您应该使用link 函数而不是controller,因为链接函数是Angular 中进行DOM 操作的默认位置。

    另外,为了避免每次实例化地图字段时都必须提供链接函数,请将链接函数放在类型定义中,而不是字段定义中。

    最后,链接函数接收封闭元素作为第二个参数,因此您只需获取封闭元素的第一个子元素即可获取div

    代码将如下所示:

    formlyConfigProvider.setType({
      name: 'leafletmap',
      templateUrl: 'leaflet-map-template.html',
      link: function(scope, el) {
        // initialize map with initial coordinates
        var initialCoordinates = [-23.0895164, -47.2187371];
        // get first child of the enclosing element - the <div>!
        var mapDiv = el.children()[0];
        var map = L.map(mapDiv, {
          center: initialCoordinates,
          zoom: 14,
          zoomControl: false
        });
      }
    });
    

    哦,我忘了告诉你两件事:

    首先,如果您想将字段键作为 ID 传递,您应该像普通的 angular 模板一样使用双花括号:

    <script type="text/ng-template" id="leaflet-map-template.html">
      <div id="{{options.key}}"></div>
    </script>
    

    最后,您不需要在 div 中输入 ID,因为我们使用封闭字段元素的第一个子元素来选择它。 :)

    总结一下,我在 codepen 上放了一个最小的工作示例,看看: https://codepen.io/sigriston/pen/OXxPPb

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-14
      • 2013-08-05
      • 1970-01-01
      • 1970-01-01
      • 2013-07-06
      • 2013-08-22
      相关资源
      最近更新 更多