Search code examples
arraysangularjsleafletng-hide

ng-hide & ng-show in leaflet legend


I tried to create a leaflet legend using the 'ng-show' and 'ng-hide' attributes.
Unfortunately, the legend is not created on site load but on map load. The attributes don't seem to work if they are added with javascript directly.

This code:

  onAdd: function() {
    var controlDiv = L.DomUtil.create('div', 'air-quality-legend');
    controlDiv.setAttribute('ng-hide', 'true');
    controlDiv.className = "airQualityIndex";
    L.DomEvent
      .addListener(controlDiv, 'click', L.DomEvent.stopPropagation)
      .addListener(controlDiv, 'click', L.DomEvent.preventDefault);
    var table = document.createElement('table');
    var tr = document.createElement('table');
    var td = document.createElement('table');
    td.innerHTML = "test";
    tr.appendChild(td);
    table.appendChild(tr);
    controlDiv.appendChild(table);
    return controlDiv;
  }

Produces that output.
As described there is a table when there should not. Is there any way to add 'ng-hide' or 'ng-show' via javascript on runtime?

Thank you for your help in advance.


Solution

  • You'll need to compile the DOM of your custom control. To do that, you'll need to inject $compile into your controller, then after having added the control to your map use the getContainer method on your control instance and run $compile on it and attach it to the scope:

    Control:

    L.Control.Custom = L.Control.extend({
        onAdd: function () {
            var container =  L.DomUtil.create('div', 'leaflet-control-custom')
                header = L.DomUtil.create('h1', 'leaflet-control-custom-header', container);
    
            header.textContent = 'NG-Hide test';
            header.setAttribute('ng-hide', 'hide');
    
            return container;
        }
    });
    

    Controller:

    angular.module('app').controller('controller', [
                 '$scope', 'leaflet', '$compile',
        function ($scope,   leaflet,   $compile) {
            $scope.hide = false;
            leaflet.map.then(function (map) {
                var control = new L.Control.Custom().addTo(map);
                $compile(control.getContainer())($scope);
            });
        }
    ]);
    

    Here's a working example on Plunker: http://plnkr.co/edit/xzRwTp9OZ8Zp8v7ktt2c?p=preview