I know that my question is related to this post, but I wonder if there is an AngularJS specific way to address this issue.
Here is the deal:
I'm using ES6 Class and ControllerAs
in my Angular directives, so controllers are declared like so:
class myCtrl {
constructor ( $log ) {
'ngInject';
// Dependency Injections
var privateLog = $log; // Private but scoped to constructor
this.publicLog = $log; // Public
// Default attributes
this.foo = 'bar';
this.publicLog.log('it works in constructor'); // logs 'it works in constructor'
privateLog.log('it works in constructor'); // logs 'it works in constructor'
}
logSomething () {
this.publicLog.log('it works in class method'); // logs 'it works in class method'
try {
privateLog.log('it works in class method');
}
catch(e) {
console.log(e); // Uncaught ReferenceError: privateLog is not defined
}
}
}
var test = new myCtrl();
test.logSomething();
test.publicLog.log('is public'); // logs 'is public'
try {
test.privateLog.log('is private');
}
catch(e) {
console.log(e); // Uncaught TypeError: Cannot read property 'log' of undefined
}
The thing is that I want to have access to my dependency injections in all classe methods, but I don't want them to be reachable publicly from the outside.
Moreover I don't want to declare my methods in the constructor as I don't want them to be redeclared for each instance.
Is there a proper way to do this or am I missing something ?