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?
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.
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.
AngularJS provides a supreme Dependency Injection mechanism. It provides following core components which can be injected into each other as dependencies.
this.logger = $log;
As you pointed out, is the way. Since it's an object, there is no global scope.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With