Javascript 如何使用formly自定义模板初始化传单地图?
我使用Angular Formly创建了一个表单,在这里输入地址,然后从本地返回一个映射。我使用以下内容创建了一个自定义模板:Javascript 如何使用formly自定义模板初始化传单地图?,javascript,angularjs,leaflet,angular-formly,Javascript,Angularjs,Leaflet,Angular Formly,我使用Angular Formly创建了一个表单,在这里输入地址,然后从本地返回一个映射。我使用以下内容创建了一个自定义模板: 并将类型设置为角度。与其他模块一起使用模块: var app = angular.module('formlyExample', [ 'ngAnimate', 'ngSanitize', 'ngTouch', 'formly', 'formlyBootstrap', 'ui.bootstrap' ], functi
并将类型设置为角度。与其他模块一起使用模块:
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
,这不起作用,因为在DOM中没有具有正确ID的元素时会调用控制器,因为Formly还没有应用模板
所以。。。如何修复它?首先,您应该使用链接
函数,而不是控制器
,因为链接函数是执行角度DOM操作的默认位置
另外,为了避免每次实例化映射字段时都必须提供链接函数,请将链接函数放在类型定义中,而不是字段定义中
最后,link函数接收封闭元素作为第二个参数,因此要获取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
});
}
});
formlyConfigProvider.setType({
名称:“传单地图”,
templateUrl:“传单地图模板.html”,
链接:功能(范围,el){
//使用初始坐标初始化地图
变量初始坐标=[-23.0895164,-47.2187371];
//获取封闭元素的第一个子元素-the!
var mapDiv=el.children()[0];
var map=L.map(mapDiv{
中心:初始坐标,
缩放:14,
动物控制:错误
});
}
});
哦,有两件事我忘了告诉你:
首先,如果要将字段键作为ID传递,则应该像常规角度模板一样,使用双大括号:
<script type="text/ng-template" id="leaflet-map-template.html">
<div id="{{options.key}}"></div>
</script>
最后,您不需要在该div
中添加ID,因为我们使用封闭字段元素的第一个子元素来选择它。:)
最后,我在codepen上提供了一个简单的工作示例,请看: