【问题标题】:Angular Leaflet Search control eventAngular Leaflet Search 控制事件
【发布时间】:2016-02-13 08:41:17
【问题描述】:

我有一个 AngularJS 应用程序,我目前正在尝试访问 Leaflet Search 控件的“search_expanded”事件,但没有运气。

这是我的代码:

angular.module('myApp', [ 'leaflet-directive' ])
       .controller('ShowMapCtrl', ["$scope", "leafletData", function ($scope, leafletData) {
       // some code
            leafletData.getMap().then(function(map) {
                       map.on('search_expanded', function(e){
                            alert("search control expannded"); 
                       });
                   });

【问题讨论】:

  • 尝试做..$scope.$on('search_expanded', console.log);
  • 那是我的第一种方法,但没有奏效
  • $rootScope.$on('search_expanded', console.log); 第二种方法?
  • angular.element(document).on('search_expanded',console.log); 第三种方法?
  • 这很奇怪..你安装了 jQuery 吗?

标签: angularjs leaflet angular-leaflet-directive


【解决方案1】:

search_expanded 事件以及L.Control.Search 支持的所有其他事件都在实际控件实例上触发,而不是在地图实例上触发,如下例所示:

var controlSearch = new L.Control.Search({
    layer: new L.LayerGroup()
}).on('search_expanded', function () {
    console.log('search_expanded!')
}).addTo(map);

http://plnkr.co/edit/njeXYb4PfbaG3hppcgmO?p=preview

【讨论】:

  • 是的,但angular-leaflet-directive 有一种不同的implementing the search control 方式,它无法执行传统的事件捕获方式
  • 我知道并且很遗憾地说 afaik 无法从 leafletControlHelpers 获取搜索控件实例,因为控件未存储在公开可用的属性中。因此,您剩下的唯一解决方案是在控制器中获取地图实例并手动将控件添加到其中。我知道这很糟糕。使用这个指令有严重的缺点,比如它臃肿,并且在使用您自己的指令运行普通 Leaflet 并将所有逻辑放在您的控制器或服务中时,您可以获得一半的功能。祝你好运。
  • 我也一直在寻找助手。难怪我找不到任何可以用来获取事件的东西。我找到了一个解决方法。这有点草率,但确实有效。
  • @schizoskmrkxx 愿意分享吗?
  • @Stephan 我刚刚取消了我草率的解决方法。请检查我的答案。但最终我还是选择了 iH8 的回答。
【解决方案2】:

首先我会尝试在那里抛出一些异常处理:

leafletData.getMap().then(function(map) {
    map.on('search_expanded', function(e){
        alert("search control expannded"); 
    }, function(reason) {
        alert('Failed: ' + reason);
});

另外,我更喜欢使用 console.log(),而不是 alert,尤其是 Angular 应用程序。

leafletData.getMap().then(function(map) {
    map.on('search_expanded', function(e){
        console.log("search control expannded"); 
    }, function(reason) {
        console.log('Failed: ' + reason);
});

【讨论】:

  • 谢谢,但问题不是承诺。它每次都成功返回承诺。问题是我不知道如何在触发时捕获“search_expanded”事件。
【解决方案3】:

我想出了一个草率的解决方法,因为该指令不允许我捕获搜索控件事件。

var expanded = false;

$scope.$on('leafletDirectiveMap.layeradd', function(){

    $('input.search-input').focus(function(){

        expanded = !expanded;

        if(expanded)
        {
            console.log("search control expanded");
        }

    });
});

【讨论】: