3

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 ?

Here is the Fiddle

Community
  • 1
  • 1
Freezystem
  • 4,494
  • 1
  • 32
  • 35

1 Answers1

0

If you want to keep injectables private, use classical angular controller structure, like this

function MyCtrl($log) {
   'ngInject';
   this.logSomething = function(message) {
       $log(message);
   }
}

Now actual $log is hidden in closure, but logSomething publicly available for templates.

UPD. If you want to keep using ES6 classes for some reason, you can try to use any existing methods to make some class member as private. There is a review of possible ways to do it.

Community
  • 1
  • 1
just-boris
  • 9,468
  • 5
  • 48
  • 84
  • Yeah that's what I think I'll be force to do, but I was interested in finding a workaround I could use to make this work with ES6 Class. =( – Freezystem Feb 12 '16 at 10:35