Revealing private and protected Typescript members within Angular 1.x's view

When integrating TS and Angular, I've noticed that everything in my controller is accessible from the view. For example, myPrivate will be visible on $ctrl.

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

Is there a way to address this concern?

Answer №1

Upon examining the generated javascript, it becomes evident why.

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

Your private property is treated like any other property on your controller.

To view the complete transpilation click here.

An effective solution would be to utilize a parameterized base controller that can define a view model for the view to utilize, instead of using the regular $ctrl.

Implementation would resemble the following:

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 access the necessary properties using the viewModel property.

I have personally applied this approach in a project with successful results. More information and a template I used as a starting point can be found here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

next.js users may encounter a problem with react-table not rendering correctly

Encountering difficulties while attempting to integrate a basic table function into my upcoming application. Despite being a sample output, the function fails to load into the index for some unknown reason! // Layouts import Layout from "../components ...

What could be the reason why modifications made to $scope in a directive's link function do not appear on the user interface?

The AngularJS directives' link function causes changes to isolate scope data that are not reflected in the UI. Take a look at this example: var myApp = angular.module('myApp', []); myApp.directive('myDirective', function () { ...

AngularJS event listener fired twice

Currently, I am facing a scenario where one controller is sending out the event, while another controller is set up to listen for it. The code looks like this: In controller A, there is a method defined as follows: $scope.process = function () { var t ...

Display a div element for a specified amount of time every certain number of minutes

I am currently utilizing AngularJS, so whether the solution involves AngularJS or pure JS does not make a difference. In the case of using AngularJS, I have a parameter named isShowDiv which will determine the switching between two divs based on the follow ...

Angular Material Popup - Interactive Map from AGM

I am in the process of developing a material dialog to collect user location information using AGM (angular google maps). I have successfully implemented a map on my main page, but when the dialog is opened, it only shows a blank space instead of the map. ...

Angular encountered a SyntaxError due to an unexpected curly brace } character

After spending a lengthy hour trying to troubleshoot this issue, I am at a loss as to why it is not functioning correctly. I have been attempting to showcase a row of images on a webpage using Angular based on data fetched from a json file. Unfortunately, ...

Using angular 1.X with webpack can be challenging and may cause compatibility issues

I am currently integrating webpack into my existing angularjs [1.4.7] application. I have a custom module that is being bundled using webpack and later added as a dependency in another module. While there are no errors during the bundling process, I encoun ...

Instead of returning an object, the underscore groupBy function now returns an array

Currently, I am attempting to utilize underscore to create an array of entities that are grouped by their respective locations. The current format of the array consists of pairs in this structure { location: Location, data: T}[]. However, I aim to rearran ...

Tips for effectively utilizing TypeORM transactions

I'm encountering an issue with transactions in TypeORM. Here's a snippet of the code causing me trouble: const someFunction = async () => { try { await this.entityManager.transaction(async (manager) => { //some opera ...

The argument type 'MatSort | null' cannot be assigned to the parameter type 'MatSort' in this scenario

When attempting to retrieve sorted data from MatTableDataSource, I used the following code: this.source = this.dataSource.sortData(this.dataSource.filteredData,this.dataSource.sort); Unfortunately, I encountered an error message: Argument of type ' ...

JavaScript function encountered an error due to an expected object

Currently, I am in the process of developing an application using VS2015, JavaScript, Angular, and MVC 5. Here is an excerpt of my JavaScript code: var myApp = angular.module('QuizApp', []); myApp.controller('QuizController', [&apos ...

Is it appropriate to include this jquery code within an angular controller?

When creating a list of rows in an HTML table using ng-repeat, I encountered an issue with styling radio buttons using jQuery. The code snippet below shows the jQuery script used to apply the style: <script> $(document).ready(function () { $('. ...

Setting a Value?

Within the services.js/Cordova file, I am encountering an issue with the following code: .factory('GCs', ['$http', function($http) { var obj= {}; $http.post("mydomina.com?myrequest=getbyid", { "id": "1"} ) ...

What is the key to ensuring the content in your canvas adapts to different screen sizes

Greetings! I wanted to extract the values from this specific meta tag: <meta name="viewport" property="viewport" content="width-device-width, initial-scale=1"> To retrieve content from a meta tag using JavaScript, I used the following code snippet: ...

What could be the reason behind the login button not triggering the console message display?

I've decided to delve into web server development on my own and have been tweaking a GitHub repository for ExpressJS with Typescript that I stumbled upon. My initial goal is simple - just to have something displayed on the console when I click the log ...

Constructor polymorphism in TypeScript allows for the creation of multiple constructor signatures

Consider this straightforward hierarchy of classes : class Vehicle {} class Car extends Vehicle { wheels: Number constructor(wheels: Number) { super() this.wheels = wheels } } I am looking to store a constructor type that ext ...

The expiration of the Gitlab CI/CD cache leads to the failure of the build process

I have an AWS CDK application in TypeScript and a simple GitLab CI/CD pipeline with 2 stages for deployment: image: node:latest stages: - dependencies - deploy dependencies: stage: dependencies only: refs: - master changes: - ...

Generating output from a callback function in TypeScript

When I execute a graphql query, the showUsers function is supposed to display all users (styled as boxes). However, at the moment, nothing is showing up. I am utilizing a functional component instead of a class component. This function is invoked after m ...

Angular2 - how can I effectively organize the logic between my components and services?

Within my current project setup, I have the following structure implemented: I have a Component that interacts with a Service Class which in turn calls an external API. The specific logic that I need to implement is related solely to the user interface. ...

What causes the oninput event to act differently in Angular as opposed to regular JavaScript?

As I delve into learning Angular with TypeScript, I've encountered some inconsistencies compared to JavaScript that are puzzling me. Take for example this function that works flawlessly with pure JavaScript, where it dynamically sets the min and max a ...