0

I have a problem adding a function-call to html in the AngularJS Controller.

UPDATE: Okay I have to be a little bit more concrete:

My Problem is about a leaflet popup with a button inside. The geojson data loads asynchronous and I have a "onEachFeature" function to add the popup - the function looks like: (IT'S SIMPLIFIED!)

.controller('MapCtrl', function($scope, $state) {
  function oef(feature, layer) {
    var bounds = layer.getBounds();
    var center = bounds.getCenter();

    var marker = L.marker(center).addTo(MAP);

    var popup = new L.Popup({
        autoPan: false,
        keepInView: true,
        closeButton: false,
        offset: new L.point(0, -5)
     }).setContent("<div><a ng-click='test()'>"+feature.properties.tooltip + "</a></div>");


   }

   //LOADING AND ADDING DATA TO MAP
   ....
   //END

   $scope.test = function(){
     alert("HI");
   }
});

Any ideas?

4
  • Why do you have HTML code inside your controller and not the view? Commented Dec 5, 2016 at 16:31
  • I changed my code above - so now it should be a little bit more understandable Commented Dec 5, 2016 at 20:35
  • @nrhode didn't you get it working with the Angular's $compile'? Commented Dec 6, 2016 at 14:00
  • No, the problem is, that the popup get initialized on the click event on the map. So I need to compile after calling the popup. That wan't work... But yes, for "normal" cases your code works well! Commented Dec 6, 2016 at 19:35

1 Answer 1

2

You need to compile your html in order to allow angular to interpret "the angular code" in the html (See https://docs.angularjs.org/api/ng/service/$compile), otherwise it's just a simple string in the "angular world". See the sample listed below.

angular.module('myapp', [])
  .controller('foo', function($scope, $compile) {

    var div = "<div><a ng-click='hello()'>Hi</a>";
    var parent = angular.element(document.querySelector('#target')).append(div)
    $compile(parent.contents())($scope);

    $scope.hello = function() {
      console.log("'Hi div' clicked: Hi!")
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<style type="text/css">
  .hand {
    cursor: hand;
    cursor: pointer;
  }
</style>

<div ng-app="myapp">

  <div ng-controller="foo">
    <div id="target" class="hand"></div>
  </div>

</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.