Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency Injections are undefined in controller functions while using Angular1+ ES6, with controller as a class

I am using ES6 class to define my controller so this is the syntax,

export class SearchBarController {
    constructor($log) {
        'ngInject';

        $log.debug("Hello");
    }

    textTyped($log){

        $log.debug("change fired.");
    }
} 

view :

<input type="text" data-ng-model="vm.txt" data-ng-change="vm.textTyped()"/>

So "Hello" from within the constructor is getting logged fine. But, "change fired" within the typedText() function is not firing because apparently is undefined how do I make my class function textTyped() to access the $log service?

Note : If I assign $log to a class property in the constructor like,

this.logger = $log;

And then do,

this.logger.debug("Change fired.");

this works. But I am unsure if it's the right approach.

Update: Also, this approach exposes this reference to the $log service to the view bound to this controller. Is this harmful?

Is there a better solution?

like image 490
Rohit Rane Avatar asked Mar 27 '16 21:03

Rohit Rane


People also ask

Which components supports Dependency Injection mechanism in AngularJS?

Which Component can be Injected as a Dependency In AngularJS? In Angular. JS, dependencies are injected by using an “injectable factory method” or “constructor function”. These components can be injected with “service” and “value” components as dependencies.

How does Dependency Injection work in AngularJS?

Dependency Injection (DI) is a software design pattern that deals with how components get hold of their dependencies. The AngularJS injector subsystem is in charge of creating components, resolving their dependencies, and providing them to other components as requested.

Does AngularJS supports Dependency Injection?

AngularJS provides a supreme Dependency Injection mechanism. It provides following core components which can be injected into each other as dependencies.


2 Answers

this.logger = $log;

As you pointed out, is the way. Since it's an object, there is no global scope.

like image 124
George Kagan Avatar answered Oct 05 '22 06:10

George Kagan


class SearchBarController {
    constructor($scope, $log) {
        this.log = $log;

        // Scope method
        $scope.vm = this;
    }

    textTyped(){
        this.log.debug("change fired.");
    }
}

SearchBarController.$inject = ['$scope', '$log'];

Try like this

like image 23
MyruBapa Avatar answered Oct 05 '22 06:10

MyruBapa