Transform my Angular implementation to TypeScript programming

After spending a year coding Angular and seeing great progress, the buzz around TypeScript has caught my attention. While there are plenty of tutorials and blogs on the topic, there seems to be inconsistency in the recommendations. How should the app.js file be structured for TypeScript?

angular.module('angular10App', [
'ngCookies',
'ngResource',
'ngSanitize',
'ui.router',
'ui.bootstrap',
'ngStorage',
'cfp.loadingBar',
'ngAnimate'
])
.config(function ($stateProvider, $urlRouterProvider, $locationProvider) {

$urlRouterProvider
        .otherwise('/');

    $locationProvider.html5Mode(true);
});

As for the controller, I aim to remove scope from it by using 'Controller as vm' in the route config. What would be the ideal structure for this controller?

angular.module('angular10App')
.controller('ResultsCtrl', function ($scope, $stateParams, results) {

    $scope.flightType = $stateParams.flightType;
    $scope.selectedAirportDep = $stateParams.from;
    $scope.selectedAirportRet = $stateParams.to;
    $scope.depDate = $stateParams.depDate;
    $scope.arrDate = $stateParams.arrDate;
    $scope.class = $stateParams.class;
    $scope.adults = $stateParams.adults;
    $scope.children = $stateParams.children;

    $scope.results = results;
});

Answer №1

When it comes to registering a module, the process remains consistent.

angular.module('angular10App', [
'ngCookies',
'ngResource',
'ngSanitize',
'ui.router',
'ui.bootstrap',
'ngStorage',
'cfp.loadingBar',
'ngAnimate'
])
.config($stateProvider: ng.ui.IStateProvider,
            $urlRouterProvider: ng.ui.IUrlRouterProvider,
            $locationProvider: ng.ILocationProvider) {
     $urlRouterProvider.otherwise('/');
     $locationProvider.html5Mode(true);
}

As for the controller, it should be declared as a class.

module controllers {
    export interface IYourScope extends ng.IScope {
        someField: boolean;
        someOtherField: string;
    }

    export class yourController {
        constructor(private $scope: IYourScope) {
           $scope.someField = true;
           $scope.someOtherField = "something"; 
        }
    }
}

Although I prefer using the controllerAs syntax and accessing properties of the controller class (which may facilitate migration to Angular 2.0 later on), something like:

module controllers {    
    export class yourController {

        public someField: boolean;
        public someOtherField: string;

        constructor(private $scope: ng.IScope)
           this.someField = true;
           this.someOtherField = "something"; 
        }
    }
}

Then you can register this controller as usual.

angular.module('yourModule').controller('ctrl',controllers.yourController);

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

Prompt triggered within AJAX request

I am facing an issue with my ajax call in which I am trying to invoke a php function containing an alert. However, the alert is not getting triggered and instead it returns me the JavaScript code (visible inside the console). How can I successfully use an ...

What is the process for configuring environment variables in a React application?

I have set up my React app to run on http://localhost:3000, and now I am looking to configure environment variables for different environments such as development, production, staging, and local. These are the URLs for my React app in various environments ...

Issue: The system is unable to locate the "moduleIntro.js" module while executing the "http" command

I recently embarked on a journey to learn Node.js and decided to experiment with the 'http' module. Here is a snippet of the code I tried to run: var http = require('http'); http.createServer(function (req, res) { res.write('H ...

How to extract the chosen option from a bound list within an Angular application

Our goal is to avoid using 2-way binding in our component setup: <select type="text" formControlName="region" (change)="regionChanged($event)"> <option *ngFor="let region of regionsDDL" [ngValue]="region">{{region.name}}</option> ...

Is there a way to transfer ngClass logic from the template to the TypeScript file in Angular?

I am implementing dropdown filters for user selection in my Angular application. The logic for adding classes with ngClass is present in the template: <div [ngClass]="i > 2 && 'array-design'"> How can I transfer this ...

Unable to retrieve location data within the function

I've been grappling with this issue for quite some time now. I have three functions that are all functioning properly individually. However, I'm facing a challenge of retrieving the value from getUserCoordinates() and passing it to fetchCurrentTe ...

Eliminate JavaScript comments with Regex in PHP

Looking to reduce the size of HTML code with the help of PHP and Regex. Here is the minify function: public static function sanitize_output($buffer) { $search = array( '/ {2,}/', '/<!--.*?-->|\t|(?:\r?& ...

What is the best way to connect to the express.js/passport.js API using an Android device as the client

Trying to access an express.js API created with node.js and passport.js. Certain methods only work when the req.user is available. Attempting to log in with Facebook and Twitter from my client app results in a plain cookie being returned. The cookie look ...

Check if all items in the array exist in Mongodb, then update them; if not, insert

In my database, I have a collection of tags and I want to perform the following actions when a user enters an array of tags: If a tag in the array already exists, update its count If a tag in the array does not exist, insert it with a count of 0 Current ...

Add a <div> element using jQuery based on the viewport size, and implement Ajax refresh when the browser is

Hey there, I have a question as a jQuery newcomer. My objective is to include different sidebars based on the browser viewport size. This is the script I have so far: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR ...

Having difficulty in displaying database values in HTML modal using PHP

On my PHP page, I have a setup that displays data based on the fetched id from the URL. Everything is working smoothly, but when I click a button to show a modal with additional information, the modal appears blank. Here is the code snippet I am using: ...

Eliminating the 'white-space' surrounding concealed images

I am currently working on a project where I have a list of images that need to be hidden or shown based on the click event of specific <li> elements. While I have managed to achieve this functionality successfully, I am facing an issue with white spa ...

It is not possible to access fields in Firestore using Node.js

Exploring the limits of my Firestore database access with a test function: exports.testfunction = functions.https.onRequest(async (request, response) => { try{ const docRef = firestore.collection("Stocks").doc("Automobile" ...

Calculating the sum of values in a JSON array using a specific parameter in Typescript

A flat JSON array contains repetitive identifier, categoryId, and category: data: [ { "identifier": "data", "categoryId": "1", "category": "Baked goods", "product": "Aunt Hattie's", "price": "375" } ...

What is the best way to call a JavaScript function with multiple arguments from a Silverlight project?

I encountered an issue when trying to invoke a JavaScript function with multiple arguments from an HTML page. Here is what I am attempting to do: wbNavigator.Navigate(new Uri("http://localhost:56433/route.html", UriKind.Absolute)); object results = wbNavi ...

Can tabs be created without the use of javascript?

I'm currently working on implementing a tabbed box layout, and while I've come across several tutorials that use JavaScript to switch between tabs, I'm wondering if there is a way to achieve the same functionality without relying on JavaScri ...

Place a gap at a specific spot within the boundary line

Here is a CSS code snippet that displays a horizontal line: .horizontalLineBottom { border-bottom:solid #6E6A6B; border-width:1px; } Is it possible to add space at a specific position on this line? For example, _________________________________ ...

Tips for transmitting form information in a fetch call

As I was developing a nodejs server, I encountered an issue with the POST call that involves sending form input data to a remote server. Despite everything else working fine, the form data was not being received by the server. Below is the code snippet in ...

What is the best way to send information to the nested component's inner scope?

I am facing an issue with rendering a list of request/response pairs in my controller using components(directives). It appears that only string attributes are being passed to the component's scope, while objects are being ignored. You can view the f ...

JavaScript library for creating animated car movements on a map using JPG images

Looking for a way to animate a car's movement on a map? I have a map image in jpg format (not svg) and a sequence of (x,y) points ready to go! If you could recommend a JavaScript library that can help me easily create an HTML page with this animation ...