Click event on Angular leaflet marker

Currently, I am using leaflet in conjunction with Angular and have a query regarding making a button clickable within a message popup. Although I understand that I need to compile the HTML, I am struggling to implement it successfully as there are no examples available featuring a JSON request.

Any suggestions or tips would be greatly appreciated!

$http.get(searchterm).then(function(articlesResponse) {

        $scope.geonamesorte = articlesResponse.data;

        var meineMarker = {};

        for (var i = 0; i < $scope.geonamesorte.length; i++) {
            var ortObjektausListe = $scope.geonamesorte[i];

            var myobjectname = ortObjektausListe.name.replace(/[^a-zA-Z0-9]/g,'_');
            ortlat = parseFloat(ortObjektausListe.lat);
            ortlng = parseFloat(ortObjektausListe.lng);

            meineMarker[myobjectname+i] =  {
                    lat: ortlat,
                    lng: ortlng,
                    message: "<span><a href='' ng-click='dosomething()''>info</a></span>",
                    focus: false,
                    draggable: false
                };

        }

        // Displaying markers on the map
        angular.extend($scope, {
          markers: meineMarker,
            defaults:{
              tileLayer:"http://tile.stamen.com/toner-lite/{z}/{x}/{y}.png"
            }
        });

  });

Answer №1

Okay, so I came across the solution here: angular-leaflet-directive custom message HTML with Angular directives in marker popup. How can this be achieved?

However, I decided to make some modifications:

    var objName = 'location';

    var locationMarker = {};
        locationMarker[objName] =  {
                    lat: 0,
                    lng: 0,
                    name: 'example',
                    message: "<span><a href='' ng-click='doSomething()'>details</a></span>",
                    focus: false,
                    draggable: false
                };

  $scope.$on('leafletDirectiveMarker.click', function(event, arguments) {
            // Arguments will include marker information and more
            console.log(arguments);
            var markerName = arguments.leafletEvent.target.options.name; 
            var $container = $(arguments.leafletEvent.target._popup._container).find('.leaflet-popup-content'); 
            $container.empty();
            var html = "<p> This is "+markerName +" " + arguments.leafletEvent.target._popup._content + "</p>", 
              linkFunction = $compile(angular.element(html)),             
              linkedDOM = linkFunction($scope); 
            $container.append(linkedDOM);
        }); 

Answer №2

To incorporate a $compile service into a controller, follow these steps:

myMarkers[objectName+i] =  {
                    lat: locationLat,
                    lng: locationLng,
                    message: $compile("<span><a href='' ng-click='performAction()''>information</a></span>")($scope),
                    focus: false,
                    draggable: false
                };

The function performAction() must be defined within the current scope.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dependency of multiple objects in Webgl three.js

I'm struggling with object dependencies and need help. I want to create a setup where one object is dependent on two other objects. Essentially, when I modify the position of one parent object (like changing the y-Position), the dependent object (chil ...

There seems to be a hitch in the functioning of the JavaScript codes

I'm having trouble calculating the amount using jQuery. Could someone please review my code and let me know what's wrong? Here are my Javascript and jQuery codes: After making changes: $(document).ready(function() { $('.home_banner&ap ...

Issue with disabled button in Angular 2 when using Chrome's autocomplete feature

In a basic login form, the login button is initially disabled with the following code: [disabled]="!password || !loginName" When Chrome's autocomplete feature fills in the values for loginName and password, the button remains disabled after the pa ...

JQUERY confirm dialog causing AJAX malfunction

I am encountering an issue where I am trying to execute an ajax function only after the user confirms a dialogue using JQUERY confirm. Strangely, when I include the confirmation step, my code throws an error and does not function properly. It's worth ...

Unusual occurrence while creating a unique identifier for a React component

I am working on creating a unique identification number for each React component, which will be assigned to the component upon mounting. Here is the approach I am taking: The callOnce function is used to ensure that a specific function is only executed on ...

Performing an HTTP POST request in Angular 2

After starting my work with Angular 2 and TypeScript, everything was going great. However, I encountered an issue when working with a REST API (POST) where the console log displayed Response {_body: "", status: 204, statusText: "Ok", headers: Headers, type ...

implementing CORS on an Express server for a specific domain

I am attempting to send a cookie post-login via AJAX from my localhost to a server that is hosted elsewhere. In order to prevent any errors related to cookies, I have included the following code in my Axios setup: var instance = axios.create({ withCr ...

Develop a list of findings from the search

Is there a way to extract the name from the image shown below? return testData.then((data) => { console.log(data) var results = []; var toSearch = params.suggestTerm; data = data["data"]["0"]; console.log(" ...

What is the best way to retrieve the current user data following a page refresh?

My current approach to this functionality is shown below: angular .module('mean-starter') .factory('Auth', function($http, $state, $window, $cookies) { var currentUser = {}; return { signup: function(user) { ...

Is your prop callback failing to return a value?

I am currently utilizing a Material UI Table component in my ReactJS project and I would like to update a state variable whenever a row is selected or deselected. The Table component has an onRowSelection prop that gets triggered each time a row is is sele ...

Update the content of a div element with the data retrieved through an Ajax response

I am attempting to update the inner HTML of a div after a certain interval. I am receiving the correct response using Ajax, but I am struggling to replace the inner HTML of the selected element with the Ajax response. What could be wrong with my code? HTM ...

Dividing JSON information into parts

I am attempting to present a highchart. I have utilized the following link: Highchart Demo Link Now, I am trying this web method: [WebMethod] public static string select() { SMSEntities d = new SMSEntities(); List<str ...

Why won't the click event work in Vue when using v-if or v-show?

Attempting to trigger a click event from a div, but if v-if false is present during component rendering, the click event does not work. Here's the code snippet: export default { name: "ProSelect", data() { return { isActive: false ...

Retrieve information from a URL and transform it into a JSON array

One of my functions looks like this: function retrieveJsonDataFromWebsite(url, callback) { let chunks = []; return require('https').get(url, res => { res.setEncoding('utf8') .on('data', (chunk) => { ...

Spinning Earth orbits around the Sun

My goal is to create a 3D Solar system, starting with the Sun and Earth using THREE.SphereGeometry() var sphere2 = new THREE.Mesh(new THREE.SphereGeometry(50, 100, 100), new THREE.MeshBasicMaterial({side: THREE.DoubleSide, map:txt2})); sphere2.position.se ...

Utilizing the real module instead of resorting to mock usage

I've configured Jest as follows: jest: { configure: { testEnvironment: 'jsdom', preset: 'ts-jest', transform: {...}, moduleNameMapper: { antd: '<rootDir>/__mocks__/antd/index.tsx&apo ...

Creating immersive visualizations using Three.js and WebGL, as well as leveraging 2D canvas for rendering graphics, involves passing the getImageData

Recently diving into WebGL (and 3D graphics in general) using three.js, I'm looking to create multiple textures from a 2D canvas for rendering various meshes, each with its own unique texture. Simply passing the canvas to a new THREE.Texture() causes ...

The website encountered an error in loading with the error message "ENOTFOUND" in Cypress

All my cypress tests were running smoothly until one day they all failed to visit the target site. The error message that I received was: cy.visit() failed trying to load: https://mywebsite.com/accounts/login/ We attempted to make an http request to this ...

Ways to include text with specific choices in a drop-down menu?

Within a form, I am encountering a situation where a select box's options are pre-selected through ajax based on a previously entered value. I am now seeking a way to append additional text to these pre-selected options only. for (i in data) { $("#my ...

Displaying an array of data using ng-repeat, only showing records where the value is found within a field of another object

Within my project, I am working with two types of objects: 'ing' containing fields 'id' and 'field', and 'fObj' containing a field named 'contain'. Using ng-repeat, I am trying to display only those ' ...