Dheeraj Agrawal
Dheeraj Agrawal

Reputation: 2357

AngularJs Provider in ES6

I am trying to create a provider in angularjs with es6 but it seems its not getting injected properly ($get is not getting called). Below is my code:

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);
                }
            },
        });
    }
}

Here is my app.js

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

So I am trying to inject provider in directive but when I do so its coming as undefined. Below is my directive

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'];

Upvotes: 1

Views: 1906

Answers (1)

tasseKATT
tasseKATT

Reputation: 38490

There problem is how you register the directive:

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

Which is the same as:

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

  return new NgIntlTelInput();
});

As you see, there are no dependencies specified as parameters for the first function.

This would for example work:

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

  console.log(ngIntlTelInputPr);

  return new NgIntlTelInput();
});

Also note that you need to inject ngIntlTelInputPr instead of ngIntlTelInput in the following line:

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

Sadly, getting directives to work with ES6 classes can be pretty tricky, as the module.directive method expects a factory function rather than a constructor.

You can read more about it here: Using ES6 Classes as Angular 1.x directives

Upvotes: 3

Related Questions