Exploring the power of developing AngularJS applications using Typescript and the app

I am currently working on a basic application that utilizes Typescript and AngularJS. In my app, I have used app.js to register my controller and some route parameters:

/// <reference path="../scripts/typings/angularjs/angular.d.ts" />
/// <reference path="secondController.ts" />
/// <reference path="../scripts/typings/angularjs/angular-route.d.ts" />
module myApp {
export class Config {
  constructor($routeProvider: ng.route.IRouteProvider) {
     $routeProvider.when("/add", { templateUrl: "test.html", controller: "CategoryCtrl" })
        .when("/add2", { templateUrl: "test.html", controller: "secondController" })
        .otherwise({ redirectTo: '/list' });
  }
}
Config.$inject = ['$routeProvider'];
export class CategoryCtrl {
  constructor($window) {
     $window.alert("Hi from CategoryCtrl");
  }
}
CategoryCtrl.$inject = ['$window'];
var app = angular.module("myApp", ['ngRoute']);
app.config(Config);
app.controller('CategoryCtrl', CategoryCtrl);
app.controller('secondController', secondController);
}

This setup works perfectly fine for me. Here is how I integrate the code into my project:

div class="container" style="margin-top:10px;">
     <div class="col-md-3" ng-controller="CategoryCtrl">
        <a href="#/add" style="color:blue; font-weight:bold;">Add New Video</a><br />
        <a href="#/add2" style="color:blue; font-weight:bold;">Add New Video2</a>
     </div>

Everything seems to be running smoothly so far. I also have a separate file named "secondController.ts", which looks like this:

module myApp {
export class secondController {
  constructor($window) {
     $window.alert("Second Controller");
  }
}
secondController.$inject = ['$window'];
}

Despite having already registered this controller in my app.js (app.ts), changing "ng-controller='CategoryCtrl'" to "ng-controller='secondController'" does not seem to work as expected. Interestingly, if I directly copy the code from secondController.ts-file into my app.ts, everything functions correctly. Unfortunately, I am unable to identify the error and would greatly appreciate any assistance.

Answer №1

To successfully implement the changes, you must follow these steps:

/// <reference path="../scripts/typings/angularjs/angular.d.ts" />
/// <reference path="secondController.ts" />
/// <reference path="../scripts/typings/angularjs/angular-route.d.ts" />
module myApp {
export class Config {
  constructor($routeProvider: ng.route.IRouteProvider) {
     $routeProvider.when("/add", { templateUrl: "test.html", controller: "CategoryCtrl" })
        .when("/add2", { templateUrl: "test.html", controller: "secondController" })
        .otherwise({ redirectTo: '/list' });
  }
}
Config.$inject = ['$routeProvider'];
export class CategoryCtrl {
  constructor($window) {
     $window.alert("Hi from CategoryCtrl");
  }
}
CategoryCtrl.$inject = ['$window'];
export var app = angular.module("myApp", ['ngRoute']);
app.config(Config);
app.controller('CategoryCtrl', CategoryCtrl);

}

The line below has been removed:

app.controller('secondController', secondController);

Add this new line:

export var app = angular.module("myApp", ['ngRoute']);

This change allows the variable 'app' to be accessed outside of the module.

In your secondController file, include the following line:

myApp.app.controller('secondController', secondController);

Your secondController file should now resemble this:

module myApp {
    export class secondController {
      constructor($window) {
         $window.alert("Second Controller");
      }
    }

secondController.$inject = ['$window'];
myApp.app.controller('secondController', secondController);
}

Prior to making these adjustments, the app.ts file referred to "secondController," with no knowledge of what this variable represented since SecondController.ts had not yet loaded.

By making the 'app' variable public, we can register new controllers after their definition is set.

I suggest applying a similar method to CategoryCtrl by separating its definition into its own file, and then registering it with Angular just as done with secondController.

By doing so, you can easily add and register multiple files without complication.

Answer №2

It may be beneficial to consolidate them into one file:

/// <reference path="../scripts/typings/angularjs/angular.d.ts" />
/// <reference path="secondController.ts" />
/// <reference path="../scripts/typings/angularjs/angular-route.d.ts" />
module myApp {

export class Config {
  constructor($routeProvider: ng.route.IRouteProvider) {
     $routeProvider.when("/add", { templateUrl: "test.html", controller: "CategoryCtrl" })
        .when("/add2", { templateUrl: "test.html", controller: "secondController" })
        .otherwise({ redirectTo: '/list' });
  }
}
Config.$inject = ['$routeProvider'];

export class CategoryCtrl {
  constructor($window) {
     $window.alert("Hi from CategoryCtrl");
  }
}
CategoryCtrl.$inject = ['$window'];

export class secondController {
  constructor($window) {
     $window.alert("Second Controller");
  }
}
secondController.$inject = ['$window'];

var app = angular.module("myApp", ['ngRoute']);
app.config(Config);
app.controller('CategoryCtrl', CategoryCtrl);
app.controller('secondController', secondController);
}

Motivation

Ensure the script tags are arranged correctly, with the controller defined prior to registering it with angular.

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

This issue arises when using AngularFire for an AngularJS voting application, where the app is unable to properly

When using ng-repeat to display array data from Firebase, I am facing an issue with counting the votes for each quote. Despite my attempts to iterate through the data, the result always comes back as undefined. My Markup <div ng-repeat="q in quote ...

Creating an AngularJS directive specifically for a certain <div> tag

Recently, I began learning angularjs and came across a script to change the font size. However, this script ended up changing all <p> tags on the entire webpage. Is there a way to modify the font size of <p> tags only within the <div class=" ...

Use AngularJs service injected in run closure for testing purposes

Testing an angularjs service called MyService has been a bit challenging. It seems like Angular tries to use the service before it is fully loaded when I try to inject it directly. However, if I mock MyService using $provide, it does work but then I don&ap ...

Utilize an array as the response model in Amazon API Gateway using the AWS CDK

I am currently in the process of developing a TypeScript AWS CDK to set up an API Gateway along with its own Swagger documentation. One of the requirements is to create a simple endpoint that returns a list of "Supplier", but I am facing challenges in spec ...

Leverage the template pattern in React and react-hook-form to access a parent form property efficiently

In an effort to increase reusability, I developed a base generic form component that could be utilized in other child form components. The setup involves two main files: BaseForm.tsx import { useForm, FormProvider } from "react-hook-form" expor ...

Can I prepend a string to the value in ng-select?

Is it possible to add a prefix before the value in ng-select? I am currently using the mixItUp plugin and would like to display filter values in a dropdown, however, mixitup requires a "." in the option value. This is the current output: <select clas ...

Zod: ensure at least one field meets the necessary criteria

Currently, I am in the process of developing a form that allows users to input either their email address or phone number. While they have the option to provide both, they are required to enter both before proceeding. For this project, I am utilizing Zod a ...

Is it possible to assign a string literal type as a key in TypeScript mappings?

Is it possible to map a string literal type as a key in a new type? I attempted this, but it did not work as expected. const obj = { type: "key", actions: { a() {}, b() {}, }, } as const; /* Map to { key: { a() {}, b() {}, } */ t ...

Issue with Nuxt2 CompositionAPI: Unable to showcase imported render function in component - Error message states "template or render function not defined"

I have created a render function that I believe is valid. I am importing it into a component and registering it within the defineComponent. However, when running the code, I encounter an error saying "template or render function not defined". I am confide ...

Which tool would be better for starting a new Angular project: angular-seed or yeoman?

I'm having trouble deciding on the best approach to create a new AngularJS application. There seem to be various methods available, such as using angular-seed from https://github.com/angular/angular-seed or yeoman - http://www.sitepoint.com/kickstar ...

Retrieve a file from an AWS S3 bucket using AngularJS

Currently utilizing angularjs. I am in need of incorporating a download feature. <button class="btn btn-labeled btn-info" title="download"> <a href="link provided by s3" download="downloaded">Download</a> </button> I have ...

What is causing my directive to throw the $unknown provider error?

encountering an unknown provider error: [$injector:unpr] http://errors.angularjs.org/1.4.3/$injector/unpr? p0=postbuttonsProvider%20%3C-%20postbuttons%20%3C-%20RandomBusinessCtrl take a look at my code : the directive is defined as below : angular.mod ...

Using Tailwind classes as a prop functions correctly, however, it does not work when directly applied

Here's a component snippet I'm working on: export const TextInput = ({ label, wrapperClassName = "", inputClassName = "", labelClassName = "", placeholder = "", ...props }: InputProps & Fiel ...

Utilizing Google Sheets as a secure, read-only database for Angular applications without the need to make the sheet accessible to the

Seeking a way to utilize Google Sheets document as a read-only database for my Angular application, I have attempted various methods. However, the challenge with all these approaches is that they necessitate public sharing of the Sheet (accessible to anyon ...

Update the ng-view within ng-view with new content

Greetings, I am currently in the process of developing a single page application using Angular. Below is an excerpt from my index.html file: <!DOCTYPE html> <html lang="en" ng-app="onlineApp"> <head> <meta charset="UTF-8"> ...

Do ES6 features get transpiled into ES5 when utilized in TypeScript?

After implementing ES6 features such as template strings, arrow functions, and destructuring in a TypeScript file, I compile the code to regular JavaScript... Does the TypeScript compiler also compile the ES6 syntax, or do I need to utilize another compil ...

Nested ng-repeat for dynamic variable rendering

I am facing an issue where I have a nested ng-repeat directive. I am attempting to create a dynamic second ng-repeat, using a key from the first one, but the current syntax is not working. Is there a different way to achieve this? Perhaps a different nota ...

The Angular UI nested State template fails to load

Index.html <!doctype html> <html ng-app="testApp"> <head> <meta name="viewport" content="width=device-width"> <link rel="Shortcut Icon" type="image/ico" href="img/favicon.png"> <link rel="stylesheet" href=" ...

SwitchMap in Typescript allows you to switch to a

In my TypeScript code, I have implemented multiple interfaces, components, and a key/interface map. interface FooProps { 'keyInFoo': string } const Foo = (props: FooProps) => {} interface BarProps { 'keyInBar': string } cons ...

Inability to assign a value to an @input within an Angular project

I recently started using Angular and I'm currently trying to declare an input. Specifically, I need the input to be a number rather than a string in an object within an array. However, I'm encountering difficulties and I can't figure out wha ...