jvrnt
jvrnt

Reputation: 655

Typescript private and protected members exposed to angular 1.x view

It seems like when combining TS and angular, everything i have on a controller is exposed to the view. In my case, myPrivate will appear on $ctrl.

class MyController extends BaseController implements SomeInterface {
    private myPrivate: string = 'myPrivateString';
}

Is there any workaround around this issue?

Upvotes: 1

Views: 703

Answers (1)

toskv
toskv

Reputation: 31600

It's pretty obvious why when you look at the generated javascript.

var MyController = (function (_super) {
    __extends(MyController, _super);
    function MyController() {
        _super.apply(this, arguments);
        this.myPrivate = 'myPrivateString';
    }
    return MyController;
}(BaseController));

Your private property ends up as any other property on your controller.

You can see the full transpilation here.

A solution would be to have a parameterized base controller able to set something like a view model for the view to use, instead of the regular $ctrl.

It would look something like this:

class BaseController<T> {

    protected scope;
    protected viewModel: T;

    constructor(scope: any, modelType: { new (): T; }) {
        this.scope = scope;

        this.viewModel = new modelType();

        this.scope["viewModel"] = this.viewModel;
    }
}

class MyParticularViewModel {
    public somethingForTheView: string;
}

class MyController extends BaseController<MyParticularViewModel> implements SomeInterface {
    private myPrivate: string = 'myPrivateString';

    constructor(scope) {
        super(scope, MyParticularViewModel);
    }
}

In the view you can then use the viewModel property to access the needed properties.

I have used this in a project in practice and it worked out pretty well. You can see a starter template that I used here for more info.

Upvotes: 1

Related Questions