ES6 Implementation of AngularJS Provider

I'm facing an issue with creating a provider in angularjs using es6 as it doesn't seem to be injected properly ($get is not being called). Check out the code snippet below:

export default class NgIntlTelInputProvider {
    constructor() {
        this.props = {};
        this.setFn = (obj) => {
            if (typeof obj === 'object') {
                for (var key in obj) {
                    this.props[key] = obj[key];
                }
            }
        };
        this.set = this.setFn;
    }

    $get() {
        return Object.create(this, {
            init: {
                value: (elm) => {
                    if (!window.intlTelInputUtils) {
                        console.log('intlTelInputUtils is not defined. Formatting and validation will not work.');
                    }
                    elm.intlTelInput(props);
                }
            },
        });
    }
}

Below is my app.js file:

angular.module('sample-app', [ngRoute])
    .config(routing)
    .provider('ngIntlTelInputPr', NgIntlTelInputProvider)
    .directive('ngIntlTelInput', () => new NgIntlTelInput());

While trying to inject the provider into the directive, it's showing up as undefined. Here's my directive implementation:

export default class NgIntlTelInput {
    constructor(ngIntlTelInputPr, $log, $window, $parse) {
        this.restrict = 'A'; 
        this.require = 'ngModel'

        this.ngIntlTelInputPr = ngIntlTelInputPr;
        console.log('Provider:', ngIntlTelInputPr)
    }
}

NgIntlTelInput.$inject = ['ngIntlTelInput', '$log', '$window', '$parse'];

Answer №1

The issue lies in the way the directive is registered:

.directive('ngIntlTelInput', () => new NgIntlTelInput());

This is equivalent to:

app.directive('ngIntlTelInput', function () {

  return new NgIntlTelInput();
});

Notice that the first function does not specify any dependencies as parameters.

An example of a correct registration would be:

app.directive('ngIntlTelInput', function(ngIntlTelInputPr) {

  console.log(ngIntlTelInputPr);

  return new NgIntlTelInput();
});

Additionally, make sure to inject ngIntlTelInputPr instead of ngIntlTelInput in the following line:

NgIntlTelInput.$inject = ['ngIntlTelInput', '$log', '$window', '$parse']

Unfortunately, making directives work with ES6 classes can be challenging, since the module.directive method expects a factory function rather than a constructor.

For more information, refer to: Using ES6 Classes as Angular 1.x directives

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

Assign the value of a state by accessing it through a string path key within a complexly

I'm currently attempting to modify a deeply nested value in an object by using a string path of the key to access the object. Here is my setup: const [payload, setPayload] = useState({ name: "test", download: true, downloadConfi ...

What is the ideal amount of HTML code to include in an Angular controller?

What are the implications of storing long paragraphs in controllers? For instance, if you have to display multiple lengthy paragraphs using ng-repeat, you may create a data structure like this within your controller: $scope.paragraphs['300 word para ...

Issue encountered while importing TypeScript files from an external module in a Next.js project

Encountering an issue within my Next.js project with the following project structure: ├── modules/ │ └── auth/ │ ├── index.ts │ ├── page.tsx │ └── package.json └── nextjs-project/ ├─ ...

Dealing with php errors post ajax request

I'm currently experiencing difficulties retrieving errors from a php script that is being called through Ajax. I have an ajax function that is linked to a deletion script. Below is my Javascript code : $('.js-delete-link').click(function ...

Endless cycle utilizing setState and onClick arrow function

In my current project using Next.js version 13, I am fetching all genres from a movie database API within a server component. These genres are then stored in the allGenres variable: import { fetchData } from "@/src/helpers/helpers"; import { Medi ...

issue with manipulating hidden field on the client side

After some troubleshooting, I discovered an issue with a hidden field in my form. Despite changing the value using JavaScript right before submitting the form, on the server side it appeared to be null or empty. The Request.Form["hidAction"] showed as em ...

Concealed images and secret thumbnails in an exquisite display

As a newcomer to fancybox, I'm unsure if what I have in mind is feasible. On my website, I have thumbnail fliers that unveil a full gallery when clicked. Is it doable to integrate thumbnail helpers into the gallery once the flyers are clicked? I under ...

Unable to transmit form information using HTML/JavaScript/Express Node application

I'm facing a challenge in developing an app that allows me to input event information and then display it on a map. I'm encountering difficulties at the initial stage when it comes to saving the data. Even though Chrome's Inspect tool indica ...

Utilize Ajax to display detailed product information within a modal using Django

In my application, the main purpose is to showcase a collection of furniture items on the homepage. Each furniture item has a quick preview button that, when clicked, should display detailed information about that specific item. I attempted to integrate aj ...

Avoid displaying incorrect UI states while data is being loaded

Within my Vue application version 2.6.X, I utilize single-file components similar to the following structure: <template> <div> <div v-if="users.length"> <!-- users list rendering here --> </div> & ...

Can individuals be invited to join using Discord.js outside of the server?

Currently, I am utilizing Signavio Workflow Accelerator to create a process for employee onboarding. As part of this process, I need to incorporate a Rest-API. The idea is for the new employee to input their Discord name or email, and then automatically re ...

angular $stateProvider behaving unexpectedly with routing

Within my main file titled index.html, I have incorporated the following basic markup... <body ng-app="starter" ng-controller="AppCtrl"> <div ui-view></div> </body> In my separate file called app.js, I am utilizing $stateProvi ...

What is the reason for ng-submit not being prevented by a mandatory select field?

In an HTML5 form, when a select element is required and no option is selected, the appropriate styling for invalidation is applied. However, the ng-submit still allows the form to be submitted. Why does this occur and is there a way to prevent submission ...

Executing program through Socket.io alert

My NodeJS server sends notifications to clients when certain actions are performed, such as deleting a row from a grid. Socket.io broadcasts this information to all connected clients. In the example of deleting a row, one approach could be adding an `acti ...

What steps can be taken to ensure that the browser coordinates do not load following an asynchronous API call?

I'm having trouble loading weather data in React due to the need for browser coordinates. I attempted fetching the data asynchronously and synchronously, but it always fails to load before the API response, which is asynchronous. How can I fix this is ...

"Troubleshooting an Issue with Angular Modules Not Functioning Properly Alongside Dependent Modules

I understand how angular.module works quite well, but for some reason I can't seem to grasp this concept. Within my code, I have the following snippet: var app = angular.module("myApp", []) app.controller("MainCtrl", ...) However, my code only fun ...

Javascript canvas producing a laser beam that serves no purpose

Greetings! I am diving into JavaScript and trying my hand at creating a game. The concept is simple - a ship shooting lasers at alien spacecrafts. However, I've encountered a problem with the destroy function that has left me scratching my head. Surpr ...

Center Title on Wheelnav.js Circle

I am currently utilizing Wheelnav js and attempting to align each title within the circle’s red region. However, I seem to be overlooking something crucial in the process. Can someone please help me identify what I may be missing? Additionally, I am look ...

A guide to dynamically adding an HTML class using JavaScript

I have a login page with a text field for email and password, styled using the Bootstrap framework. I want to change the border color of the input field from grey to red when it is empty and the user clicks the login button. I tried implementing the code t ...

Place the p elements outside of the divs and align them accordingly

I have a div containing multiple p elements and I need to align buttons next to certain p elements. I want the buttons to be displayed only for specific p elements, which will be controlled using JavaScript. Normally, I would put each p element in a separa ...