Undefined dependency injections in controller functions when using Angular1 + ES6, with the controller as a class

I use the 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."); } } 

:

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

So, "Hello" from within the constructor gets the record in order. But the "change" in the typedText () function does not work, because, apparently, it is undefined, how to make my textTyped () class function access the $ log service?

Note If I assign $ log to the class property in the constructor, for example,

 this.logger = $log; 

And then do

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

it works. But I'm not sure if this is the right approach.

Refresh . In addition, this approach provides this link to the $ log service for the view associated with this controller. It's unhealthy?

Is there a better solution?

+5
source share
3 answers

In case anyone is interested, I found a more elegant solution to the problem using ES6 Object Destructuring:

 class ABCController { constructor($log, $http){ let vm = this; vm.DI = () => ({$log, $http}); } classFn(){ let vm = this; let {$log, $http} = vm.DI(); //Now use $log and $http straightway $log.debug("Testing"); $http({...}).then(); } classFn2(){ let vm = this; //you can also destructure only the required dependencies in this way let {$http} = vm.DI(); } } ABCController.$inject = ['$log', '$http']; 

This way you don't have to write ugly / confusing code like vm.DI.log etc. Moreover, in this way, DIs are less susceptible to performance in presentation.

+2
source
 this.logger = $log; 

As you pointed out, this is the way to go. Because this is an object, a global scope does not exist.

+2
source
 class SearchBarController { constructor($scope, $log) { this.log = $log; // Scope method $scope.vm = this; } textTyped(){ this.log.debug("change fired."); } } SearchBarController.$inject = ['$scope', '$log']; 

try it

+2
source

Source: https://habr.com/ru/post/1245874/


All Articles