1

How can I inject $http to the modal directive using es6? I Tried do it like this but I get $http = undefined. At finally i'm trying vcRecaptchaService but have same problem.

class ModalDirective {
    /**
     * Constructor class ModalDirective
     */
    constructor($http) {
        this.restrict = 'E',
        this.scope = {
            show: '=',
            subm: '=',
            emailState: '=',
            requestResult: '='
        },
            this.transclude = true,
        this.template = require('./modal.tpl.html');
        this.$http = $http


    }

    link(scope, attrs) {
        scope.dialogStyle = {};
        scope.formData = {};


        scope.hideModal = function() {
            scope.show = false;
        };

     console.log(this.$http);

    }
 }
 export default ModalDirective;
2
  • use "ngInject" gulp or equivalent in your build system Commented Jul 12, 2017 at 15:59
  • look into this github.com/AngularClass/NG6-starter it might help Commented Jul 12, 2017 at 16:14

2 Answers 2

2

To inject $http into an ES6 class AngularJS directive, use $inject Property Annotation:

class myDirective {
  constructor ($http) {
    this.$http = $http;
  }
  link(scope, elem, attrs) {
    console.log(this.$http);
  }
}
myDirective.$inject = ["$http"];

angular.module("app",[])
.directive("myDirective", myDirective);
<script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app=app>
    <h1>ES6 Directive Example</h1>
    <div my-directive></div>
  </body>

See also ToddMoto: AngularJS styleguide (ES2015)

Sign up to request clarification or add additional context in comments.

3 Comments

If I do it like you sad , I get $http = undefined.
The above Demo works. What are you doing differently than the above Demo?
Maybe something wrong in my modules imort file ? plnkr.co/edit/ZTwRL1E6hC5gwBPpjzAt?p=catalogue
0

You can pass a function which returns an instance of your class:

angular.module('myApp').directive('modal', ['$http', $http => new ModalDirective($http)]);

2 Comments

ES6 features (such as classes and arrow functions) are now all possible with AngularJS 1.5.
@georgeawg I had no idea you could pass a class directly to .directive now. Good to know!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.