Issues arise when attempting to bind an AngularJS directive template with OpenLayers

My custom directive focuses on developing an openlayers map application using Angular.

<div ng-app="app">
    <map-container></map-container>
</div>

If you want to check out the working code, click here:

angular.module("app",[]);

angular.module("app").controller("MapContainerController", function ($scope) {
    $scope.map = new ol.Map({});
});

angular.module("app").directive("mapContainer", function ($timeout) {
    return {
        "transclude": true,
        "controller": "MapContainerController",
        "link": function (scope) {
            var map = scope.map;
            map.setTarget(scope.targetElement || "map");
            map.addLayer(new ol.layer.Tile({
                source: new ol.source.OSM()
            }));
            map.setView(new ol.View({
                zoom: 3,
                center: [0, 0]
            }));
        },
        "template": '<div id="map" class="map" ng-transclude></div>'
    }
});

However, I want to utilize a scope parameter for the directive's map element name, as shown in this code snippet: demo version is here.

<div ng-app="app">
    <map-container  target-element="map"></map-container>
</div>

Unfortunately, this approach does not seem to work properly.

angular.module("app").directive("mapContainer", function ($timeout) {
    return {
        "transclude": true,
        "scope": {
            "targetElement": "@"
        },
        "controller": "MapContainerController",
        "link": function (scope) {
            var map = scope.map;
            map.setTarget(scope.targetElement || "map");
            map.addLayer(new ol.layer.Tile({
                source: new ol.source.OSM()
            }));
            map.setView(new ol.View({
                zoom: 3,
                center: [0, 0]
            }));
        },
        "template": '<div id="{{targetElement}}" class="map" ng-transclude></div>'
    }
});

It seems like everything is set up correctly, but unfortunately, it still doesn't work. I'm having trouble pinpointing the issue.

Answer №1

To ensure that the template is displayed with the id before creating the map, wrap your directive code in $timeout.

angular.module("app").directive("mapContainer", function ($timeout) {
    return {
        "transclude": true,
        "scope": {
            "targetElement": "@"
        },
        "controller": "MapContainerController",
        "link": function (scope) {
            var map = scope.map;

            $timeout(function() {
               map.setTarget(scope.targetElement || "map");
               map.addLayer(new ol.layer.Tile({
                   source: new ol.source.OSM()
               }));
               map.setView(new ol.View({
                  zoom: 3,
                  center: [0, 0]
               }));

            });
                    },
        "template": '<div id="{{targetElement}}" class="map" ng-transclude></div>'
    }
});

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

Is it necessary to uncheck the row checkbox when inputs are left empty after blurred?

Two issues have cropped up here. When clicking on an input within a row, the corresponding checkbox should be checked. Currently, only the first text input is able to check the checkbox due to the use of .prev(). Is there a different approach that can be t ...

Integrating Restangular with oauth-ng in Angular.js: A powerful combination for

Our Restful API now utilizes OAuth 2.0 for security. I am looking to integrate an AngularJS frontend with the help of Restangular and oauth-ng The challenge lies in getting these two to collaborate effectively with the oauth token. Oauth-ng handles logi ...

Verify the presence of plain ASCII text

I need to verify if the file uploaded is in ascii plain text format. Can you suggest a method? $("#my_file").change(function(){ //alert if file is not ascii plain text }); <input type="file" name="my_file" id="my_file" /> ...

krajee implement image insertion with screen capture

I am currently utilizing the Krajee file input plugin to upload images to a server. I am also looking to incorporate the ability to add files through screen capture. The concept is that when an image is captured, it will be displayed in the file upload pre ...

Link Google Map Marker Click Event with Dynamic Binding

I'm currently working on binding a click event to a link that is positioned outside the Google Map Canvas. The goal is to open an "infowindow" on a map marker when this link is clicked. While I know how to achieve this for a specific point, I need a d ...

Angular JS - Implementing a flexible URL structure for fetching data using $http GET

I have been working on implementing a login feature for my app by using a custom REST API. Initially, I was able to successfully authenticate by manually entering the complete URL with the username and password: http://www.myexample.com/ACTION/USER/PASSWO ...

Issue with Node.js server - appending a "/" when searching for files on browser

Currently, I am in the process of building my very first Node.js server to gain a better understanding of Angular/Node and ultimately explore the entire MEAN stack. Although my server is operational, there seems to be an issue within my code. Whenever I i ...

Use Puppeteer and Node.js to repeatedly click a button until it is no longer present, then initiate the next step

Imagine a dynamic web page filled with rows of constantly updated data. The number of rows on the page remains fixed, meaning old rows are replaced and not stored anywhere. To navigate through this page, you need to click on a "load more" button that app ...

React components can be used to dynamically render and display an array of objects through methods like reduce and

Here's the scenario at hand: (https://codesandbox.io/s/8p21n6p09l) I have an array of objects (referred to as modules) structured like this: const modules = [ { thematicArea: "Topic 1", id: 1, name: "Building assertive attitude", d ...

Replacing the yellow autofill background

After much effort, I have finally discovered the ultimate method to remove autofill styling across all browsers: $('input').each(function() { var $this = $(this); $this.after($this.clone()).remove(); }); However, executing t ...

Issue with saving Twitter stream data to MongoDB using Mongoose not being properly handled

My goal was to store data from the Twitter Streaming API into MongoDB using Mongoose. However, I'm facing an issue where only a single document is saved out of the continuous stream of data when I run the code: var mongoose = require('mongoose&a ...

Sinon - the ultimate guide to intercepting the save() function in a mongoose schema

Currently, I am in the process of writing unit tests for an API that utilizes MongoDB in conjunction with mongoose for database access. Within my codebase, there exists a model file that defines and exports a mongoose model as shown below: const { Schema, ...

Transmitting Several Pictures at Once Through WhatsApp-WebJS

I have encountered a challenge while attempting to send multiple images in a single WhatsApp message using the WhatsApp-WebJS library. Despite receiving a "success" confirmation without any errors, the images and message fail to appear on WhatsAp ...

Tips for retrieving values from multiple checkboxes that have been selected

What is the best way to retrieve and store multiple selected checkbox values in Angular.js, while separating them with a comma (, ) when sending to the database? ...

The combination of Node.js and a Telegram bot

I am trying to utilize a telegram bot to access a specific route on a website. Within the website's routes.js file, I have: app.get('/api/getalert', getAlert); and var getAlert = function(req, res) { var id = req.query.id; ...

JavaScript does not support the enumeration of programs

I'm currently working on a program that takes user input (library, authorName) and displays the titles of books written by the author. Here is an example library structure: let library = [ { author: 'Bill Gates', title: 'The Road Ah ...

experiencing difficulties utilizing the prompt package in nodeJS

Exploring the world of nodeJS as a novice, I recently dived into taking user input through the console in nodeJS. My journey led me to discover the prompt package. Here is snippet of the code I've been experimenting with: var prompt = require('p ...

What is the reason for sending a single file to the server?

A function called "import File" was developed to send multiple files to the server, but only one file is being received. Input: <input type="files" id="files" name="files" multiple onChange={ (e) => this.importFile(e.target.files) } ...

Prevent selection based on function in Angular

I'm attempting to prevent certain options from being selected based on a specific method. For instance, let's say I have four options: A B C D In my method (let's use "x" as an example): if(name == A) { disable the selection for option A. ...

Navigating Through a Route - Using Node.js

What is the most effective way to execute a GET request in a route? api.js api.route('/guests') .get(function(req, res) { Guest.find(function(err, guests) { if (err) res.send(err); res.json(guests); }); ...