2016-07-07 63 views
1

我正在使用Angular-Formly來創建一個表單,在其中輸入一個地址,並返回來自本地的地圖。我創建了一個自定義模板使用下列內容:如何使用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

回答

3

這不起作用,因爲控制器將在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,你應該做的就像一個普通的角模板,用雙花括號:

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

最後,你不必把一個ID在div,因爲我們使用的第一個孩子包圍字段元素以選擇它。 :)

把它包起來,我把一個最小的工作示例了在codepen,一起來看看: https://codepen.io/sigriston/pen/OXxPPb