utilizing $inject method along with supplementary constructor parameters

After referencing the answer found here:

Upon implementing the $inject syntax, my controller code appears as follows:

class MyCtrl {

  public static $inject: string[] = ['$scope'];
  constructor($scope){
    // implementation
  }
}
// register the controller
app.controller("MyCtrl", MyCtrl);

Now, the query arises - what if I need to pass custom arguments in addition to the injected variables into the constructor?:

class MyCtrl {

  public static $inject: string[] = ['$scope'];
  constructor($scope, customArg){
    // implementation
  }
}
// How can I successfully provide customArg without errors?
app.controller("MyCtrl", MyCtrl(customArg)); // Incorrect approach

I am under the impression that there might be a fundamental aspect I am overlooking. With this methodology, does every parameter passed into the .controller() function require registration with AngularJS? Should I avoid trying to include custom arguments altogether? Alternatively, is it possible to pass an arbitrary value or object, and if so, how would that be accomplished?

Answer №1

customArg

If you want to pass a custom argument, it won't work when Angular calls the constructor. However, you can still register other components with Angular such as Services, Factories, and Values (constants) that will be passed to the controller by Angular.

For more information, check out this video: https://www.youtube.com/watch?v=Yis8m3BdnEM&hd=1

Answer №2

Apologies for not being able to comment due to insufficient points.

I am facing a similar situation with the following scenario:

export abstract class DataService<T> {

    static $inject = ['$resource'];
    private svc: ng.resource.IResourceClass<ng.resource.IResource<T>>;

    constructor(
        protected $resource: ng.resource.IResourceService, url: string
    ) {
        this.svc = <ng.resource.IResourceClass<ng.resource.IResource<T>>>this.$resource(url, { id: '@id' });
    }

    public get(id: number): ng.IPromise<T> {
        return this.svc.get({ id: id }).$promise;
    }

}

export class MyDataService
    extends DataService<IItem> {


   // encountering a major issue here!!!
   constructor(
    ) {
        super("/api/items/:id");
    }

}

It seems like I will need to duplicate the injection in each derived class and also provide the super... making it redundant

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

Manage interfaces and structures

I am looking to implement user roles in my application. Here is a snippet of the code I would like to use: export interface User{ name: string roles: Roles[] } interface Roles{ ADMIN: new Permissions(1,1,1,1,1), MOD: new Permissions(1,0,1,1,0,0), [. ...

The unit test is running successfully on the local environment, but it is failing on Jenkins with the error code TS2339, stating that the property 'toBeTruthy' is not recognized on the type 'Assertion'

I've been tackling a project in Angular and recently encountered an issue. Running 'npm run test' locally shows that my tests are passing without any problems. it('should create', () => { expect(component).toBeTruthy();}); How ...

Verify the identity of my Angular application to enable collaboration on a GitHub repository

In my current project, I am utilizing a specific function to retrieve the list of collaborators for a particular repository. Here is the code snippet: var getCol = function(username, reponame) { var repo; var repoUrl = "https://api.gith ...

What is the best way to dynamically set minDate for a datetime-local input field?

I need assistance with setting up two input fields: one for the start date and one for the end date. I want the end date to automatically populate with the same value as the start date when the start date is filled, and have the minimum value set to be the ...

Having trouble getting your AngularJS code to work?

Recently, I decided to experiment with AngularJS and started working on a new project. Below is the HTML code I wrote: <div ng-app ng-controller="nameController"> <input type="text" value="Jack" ng-model="fname" /> <input type="tex ...

Leveraging File functionality in TypeScript

In the process of developing a web application with Angular 4 and Typescript, I encountered an issue while attempting to retrieve the date of a file for upload. Specifically, when trying to access the lastModified property of a File object, Typescript retu ...

What strategies can I implement to streamline the use of these functions instead of creating a separate one for each textfield

Currently, I am learning how to use spfx with SPO (SharePoint Online). In my form, there are multiple text fields that need to be handled. I have two class components named A and B. Whenever a textfield in component B is typed into, a function sends the in ...

"Exploring the world of server-side and client-side MVC frameworks

I recently embarked on learning ASP.Net MVC and have encountered some puzzling questions regarding the MVC framework - particularly, whether it leans more towards client-side or server-side operation. I understand if these queries seem basic, but I'd ...

What is the best way to assign default values when destructuring interfaces within interfaces in TypeScript?

My goal here is to create a function that can be used with or without arguments. If arguments are provided, it should work with those values; if not, default values should be used. The issue I'm facing is that although there are no TypeScript errors ...

The functionality of Ng-Show is acting up

$scope.stay = function() { alert("Inside Keep me In") $scope.timed = false; $scope.isLogStatus = true; } $scope.displayAlert = function() { $scope.timed = true; alert("inside display") } function idleTimer() { var t; $window.o ...

Developing pledges in AngularJS

I am currently working on implementing a promise in Angular using the $q service to retrieve an object from a web service. The unique aspect of this implementation is that if the object is already cached, it should be returned without making a call to the ...

The module instantiation in AngularJS encountered an error

Currently learning AngularJS and attempting to develop an authentication service, but encountering an error. Error: [$injector:modulerr] Failed to create module flujoDeCaja: [$injector:modulerr] Module auth failed to instantiate: [$injector:nomod] Module ...

Transforming a JSON object into XML format

Currently, I am encountering an issue while attempting to convert my JSON object to XML using the xml-js library's json2xml function. When trying to implement this functionality, I keep getting an error message that states: Error: Buffer is not defin ...

Can you explain the concept of "Import trace for requested module" and provide instructions on how to resolve any issues that

Hello everyone, I am new to this site so please forgive me if my question is not perfect. My app was working fine without any issues until today when I tried to run npm run dev. I didn't make any changes, just ran the command and received a strange er ...

Accurately locate all ChildComponents throughout the entire Component hierarchy

I am facing a challenge in Angular where I need to retrieve all the ChildComponents from my ParentComponent. The issue is that the ChildComponents are not directly nested within the ParentComponent, but instead they are children of other components which a ...

Managing Import Structure in Turborepo/Typescript Package

I am currently working on creating a range of TypeScript packages as part of a Turborepo project. Here is an example of how the import structure for these packages looks like: import { Test } from "package-name" import { Test } from "package ...

Utilizing ngClassEven and ngClassOdd in Angular 2 for Improved Styling

I attempted to replicate the behavior of ng-class-even and ng-class-odd (originally from Angular 1) in my Angular 2 application. Below is the code I wrote and it's functioning correctly, but I'm curious if there are alternative methods to achiev ...

Merging Documents in PouchDB

I need to retrieve equipment data from pouchdb/couchbase that has users assigned to them. Each piece of equipment has an _id and a checkedOutBy field with the user._id as its value. The employee object contains the user's name. How can I retrieve the ...

TypeScript observable variable not defined

Recently, I encountered an issue and made a change to resolve it. However, I am unsure if it is the correct approach... In my project, I have defined an interface: export interface ContextEnvironment { language: string; pingUrl: string; sessionFini ...

Utilizing a dynamic value in an Angular directive

For my latest project, I am working on developing a basic JSON pretty-printer directive using angular.js. Here is the code snippet I have so far: (function(_name) { function prettyJson() { return { restrict: 'E', ...