Creating functionality with a native JavaScript plugin within a directive and test suite

I have a custom JavaScript plugin that is integrated within a directive and utilized in an Angular manner.

Snippet of the directive,

export default function () {
'use strict';
return {
    restrict: 'E',
    scope: {
        map: '=',
        options: '='
    },
    replace: true,
    template: '<div id="map" class="leaflet-map"></div>'
    link: function(scope, element, attrs) {

        //Here lies the native JavaScript code that 
        //injects SVG inside the specified template

        scope.map = new MP.Map(scope.options);       

    }
  };
}

HTML

<mp-map options="opt" map="mapOpt"></mp-map>

Desired HTML Structure

<div id="map"><svg>.. content of the map .. </svg></div>

Firstly, I am attempting to access mapOpt (i.e. instance of Mp.Map or binding with the native JavaScript class in the directive's link method) on init, but failing to obtain the instance of MP.Map in the Angular controller. By using $timeout (without any asynchronous data), it works subsequently.

Secondly, I have crafted a unit test for the directive to confirm that <mp-map> gets replaced by the template of the directive. However, an error "Map container not found" (the error generated by the native code) arises during this process.

It seems like there might be an issue with how I initially defined the directive.

Calling out to fellow Angular developers for assistance.

Your prompt help would be greatly valued.


EDIT: Few excerpts from the MP class (Custom class)

FP.Map = L.Class.extend({

  options: {
              container: 'map',
              .....
           },

  ....

  // Map options
  this.options.map = L.extend(this.options.map, options.map);
  this.map = L.map(this.container, this.options.map);

})

Answer №1

An error is being thrown that says "Map container not found" (this is an error thrown by the native code).

How does your MP.map instance determine which element to use? In Leaflet, you specify the element you want to use as the first parameter and the options object as the second:

new L.Map(element[0], scope.options);
However, in your code, I see you are using: new MP.Map(scope.options); Your MP.map doesn't have information about which element to use. It's difficult to provide a solution without knowing more about MP.map. Could you please share some code or context related to Leaflet?

Having trouble accessing the instance of MP.Map in an Angular controller

Your controller code executes before the link function of your directive. So when you try to access the map instance using $scope.map in the controller, it's not available yet. There are several ways to resolve this issue:

  1. Use $watch on $scope.map and wait for the instance: http://plnkr.co/edit/N9DwdHQUIzxhqax6mwMm?p=preview
  2. scope.$broadcast an event after instantiation and catch it in your controller: http://plnkr.co/edit/QB8fXMM67FD4NgMS49j7?p=preview
  3. Bind to a callback function in your controller: http://plnkr.co/edit/PFvJzSliDo8uLFk8HgOi?p=preview
  4. Create a promise in a service and resolve it: http://plnkr.co/edit/DoJpGqtR7TWmKAeBZiYJ?p=preview

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

Issue with React-Native FlatList's scrolling functionality

Struggling with implementing a scrolling FlatList in React Native. Despite trying various solutions found on Stack Overflow, such as adjusting flex properties and wrapping elements in views, the list still refuses to scroll. Snippet of code (issue is with ...

A JavaScript object featuring a predefined value

I have a simple goal that I'm unsure about achieving. My objective is to create an object that will return a specific value if no property is specified. For example: console.log(obj) // Should output "123" console.log(obj.x) // Should output "ABC" ...

ng-options exclude the initial selection

Is there a way to make ng-options skip the first element? I attempted using ng-show="!$first", which works with ng-repeat but not with ng-options. Here is my code snippet: <select data-ng-model="minutes_per_slot" data-ng-options="slot as slot + &apos ...

Adjust the output number in a JavaScript BMI calculator to the nearest whole number when using the

Hey there, I'm currently working on a beginner project and could use some assistance. My project involves creating a basic BMI calculator using metric units, but I seem to be encountering issues with rounding numbers. Here is a snippet of my code: var ...

I need to inform users that this application is not accessible on devices with small screens

Showing this app on a small device is not supported, such as when the device width falls between 320px and 480px. ...

The challenges with implementing makeStyles in React Material UI

const useStyles = makeStyles((theme) => ({ toolbarMargin: { ...theme.mixins.toolbar, marginBottom: "3em", }, logo: { height: "7em", }, tabContainer: { marginLeft: "auto", }, tab: { ...theme ...

Execute the command "prisma migrate dev" to update the existing database

I'm currently in the process of configuring Prisma migrate on a pre-populated MySQL database in my development environment, but I'm facing challenges getting it to function correctly. 1. After executing prisma db pull successfully to generate th ...

Troubleshooting Tips: Investigating a Service Call in AngularJS 2 using ES6 Syntax

MY DILEMMA: I have recently started learning Angular2 and found myself wanting to debug a service call. The service appears to have been properly called, as evidenced by the view display. However, when trying to log the content of the variable holding t ...

Tips for changing the state of a toggle button with JavaScript

I need help creating a toggle button. To see the code I'm working on, click here. In my JavaScript code, I am reading the value of a 'checkbox'. If the value is true, I add another div with a close button. When the close button is clicked, ...

Create a pair of divs on your webpage that users can drag around using HTML5

Hello to all HTML5 developers! I am currently facing an issue where I am attempting to designate two separate divs as dragable areas for incoming files. Unfortunately, it seems that only one of them can be active at a time. How can I adjust my code so th ...

Sending reference variable from Angular input type=file

I am currently learning Angular and I have implemented a feature where a list of PDF files is displayed using an array called pdfs. In my template, these PDF files are parsed into "card" elements for better visualization. The issue arises when I attempt ...

Generate a graph showcasing the frequency of character occurrences within a specific column of a .csv file

I'm currently working on creating a graph using d3.js What I need to accomplish is reading the some_column column in a .csv file and counting the occurrences of | to plot them accordingly on the y-axis. The line should be plotted based on the number ...

Error with JSON data from the Twitch TV API

I am having trouble with the Twitch API. When a streamer is live, I work with the "Stream" property, but if they are not streaming, I need to refer to another link. I use the getJSON function to fetch the necessary API link and work with it. However, my lo ...

Get selectize.js to display only options that begin with the user's input

Using selectize.js, my current setup looks like this: Instead of only showing words that start with 'arm', it displays words or options containing 'arm' as a substring elsewhere. I want to modify the function to display only words or ...

Can anyone provide guidance on creating a Jest test for an authenticated Express endpoint?

I have been working on a seemingly straightforward 4-file toy solution that I thought was simple. I am looking to write a Jest test for the '/bingo' route in bingo.js which requires authentication. Below are the four files that make up this setup ...

Is it possible to integrate jQuery and JavaScript together?

Can I combine JavaScript selector document.querySelector with jQuery functions instead of using $ or jQuery selectors? For instance: $.getJSON("list.json", function(data) { document.querySelector("#content").html(data.name); }); When trying to use d ...

TypeORM ensures that sensitive information, such as passwords, is never returned from the database when retrieving a user

I developed a REST API using NestJs and TypeORM, focusing on my user entity: @Entity('User') export class User extends BaseEntity { @PrimaryGeneratedColumn() public id: number; @Column({ unique: true }) public username: string; publi ...

When clicking on a checkbox's assigned label, Chrome and IE may experience delays in firing the change event

When a user checks a checkbox under a specific condition, I want to display an alert message and then uncheck the checkbox. To achieve this, I am utilizing the click function on the checkbox to internally uncheck it and trigger necessary events. I have a ...

What exactly happens behind the scenes when utilizing the React hook useEffect()? Is an effect set up with useEffect able to halt the main thread

According to the documentation for the useEffect() hook in React, it states that: "Effects scheduled with useEffect don’t prevent the browser from updating the screen." Insight Unlike componentDidMount or componentDidUpdate, effects set with ...

Error message in Node.js: Unable to establish connection to 127.0.0.1 on port 21 due to E

I am currently developing a simple application using node js, and I have encountered the following issue: Error: connect ECONNREFUSED 127.0.0.1:21 at Object exports._errnoException (util.js:1034:11) at exports _exceptionWithHostPort (util.js:1057: ...