Sending data from view to controller in Angular using TypeScript

I am currently working with AngularJS and TypeScript, and I have encountered an issue with passing a parameter from the view to the controller. In my attempts to solve this problem, I have utilized ng-init as follows:

<div class="col-md-9" ng-controller="MapIZSController" ng-init="init('IZS')">

The goal here is to pass the value of "IZS" to the controller. The structure of the controller is shown below:

export class MapIZSController
{
    static $inject = ["$scope", "leafletData"];
    private m_scope: IMapIZSScope;
    private m_leafletData;

    constructor($scope: IMapIZSScope, leafletData)
    {
        // Attempt 1
        $scope.init = function (type) {
            console.log("type is: " + type);
        };
        
        // Attempt 2
        $scope.init = this.init;
    }

    public init = (init: any) => {
        console.log("init is: " + init)
    } 

The issue I'm facing is that neither the first nor the second method I tried seems to be working properly.

  • The first approach is never executed.
  • The second approach also fails to achieve the desired result.

If you have any advice or suggestions on how to resolve this issue, I would greatly appreciate it. Thank you!

Answer №1

Looks like you're heading in the right direction. You can find a working example on this plunker

Here's a simplified version of the controller:

namespace MyCustomSpace 
{   
  export class CustomMapController
  {
    static $inject = ["$scope", "leafletData"];
    private m_scope: ICustomMapScope;
    private m_leafletData;

    private _type;
    constructor($scope: ICustomMapScope, leafletData)
    {
        // $scope.init = this.init;       
    }

    public init = (type: any) => {
        this._type = type
        console.log("Type selected: " + this._type)
    } 
  }
}

You can call the init method like this:

<div class="col-md-9" 
  ng-controller="CustomMapController as ctrl" 
  ng-init="ctrl.init('Map')">
</div>

By using the `controllerAs` syntax, you can access the controller with `ctrl.` and easily call its methods like `ctrl.init()`.

Feel free to test it out 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

Converting yard values to meter values using AngularJS: A comprehensive guide

My task is to convert meter values to yard using two dropdowns. The first dropdown contains various values, while the second dropdown has "meter" and "yard" options. If "meter" is selected in the second dropdown, the values in the first dropdown remain unc ...

Issue with selecting a value in React MUI and default value not being defined

Currently, I am working on creating a form in React using MUI and Formik. While implementing the select feature with default values fetched from an API object, I encountered issues where the select function was not working as expected. Strangely, I couldn& ...

The error message "window is not defined" is commonly encountered in Next

Having some trouble with using apexcharts in a next.js application, as it's giving me an error saying 'window is not defined'. If anyone has any insights or solutions, I would greatly appreciate the help. Any ideas on what could be causing ...

Creating a function in Typescript to extend a generic builder type with new methods

Looking to address the warnings associated with buildChainableHTML. Check out this TS Playground Link Is there a way to both: a) Address the language server's concerns without resorting to workarounds (such as !,as, ?)? b) Dodge using type HTMLChain ...

organize divs in a nested angular style

Looking to showcase div elements in a specific layout within my Angular project: The current HTML structure is as follows: <div class="outer-wrapper"> <div class="image" ng-repeat="image in images" ng-if="showImages" ng-click="imageClick(ima ...

Updating the time component of a datetime object using Angular's HTTP method

I'm facing a strange bug with my API interaction through AngularJS. When trying to update something, I encounter the following code snippet: console.log('updated: ', event.startsAt); $http({ method: 'PUT', url: baseurl ...

Is there a way to integrate the AuthState TypeScript Interface into the react-oidc-context Node package for testing in Next.js?

We are currently working on a Next.js application that utilizes the react-oidc-context Node module for authentication with ADFS. During our testing phase using Vitest, we encountered the following error: TypeError: Cannot read properties of undefined (rea ...

Ionic 3: Struggling to Access Promise Value Outside Function

I've encountered an issue where I am unable to retrieve the value of a promise outside of my function. It keeps returning undefined. Here's what I have attempted so far: Home.ts class Home{ dd:any; constructor(public dbHelpr:DbHelperProvider ...

Revamp the appearance of angular material inputs

I have been working on customizing the style of an Angular Material input. So far, I successfully altered the background-color with the following code: md-input-container { padding-bottom: 5px; background-color: #222; } I also changed the placeh ...

Error Uncovered: Ionic 2 Singleton Service Experiencing Issues

I have developed a User class to be used as a singleton service in multiple components. Could you please review if the Injectable() declaration is correct? import { Injectable } from '@angular/core'; import {Http, Headers} from '@angular/ht ...

When converting to a React Functional Component using Typescript, an error occurred: The property 'forceUpdateHandler' could not be found on the type 'MutableRefObject<Spinner | null>'

Looking to convert the App component in this CodePen into a Functional component using Typescript. Encountering an error when attempting to run it: ERROR in src/App.tsx:13:14 TS2339: Property 'forceUpdateHandler' does not exist on type 'Mu ...

`Easily handle a Restangular resource``

I'm struggling with using Restangular for the first time and I'm having trouble understanding how to handle promises within my own service. I've attempted to use the customGET method but in my controller, the response is an object containing ...

Encountering a 404 error when trying to convert an AJAX API post to an $http post in AngularJS

In the process of developing a chat application that integrates with the incontact chat API, I have encountered some difficulties. Below is the documentation for the incontact chat API: function startAgentSession() { var startSessionPayload = { ' ...

Setting up SSL/TLS certificates with Axios and Nest JS

I have a Nest JS application set up to send data from a local service to an online service. However, the requests are not working because we do not have an SSL certificate at the moment. Can anyone provide guidance on configuring Axios in Nest JS to accept ...

Include a search query parameter in the URL by adding "?search=" to connect with a

In my react/typescript application, I have a client and server setup. The client requests data from the server and displays it using React. When making a request for data on the client side, this is how it's done: export const createApiClient = (): A ...

Getting a select2 value in AngularJs can be accomplished by using the ng-model

Why am I unable to retrieve the select2 value? Here's my current code snippet: <select id="categoryId" class="category" ng-model="selectedCategory" ng-options="selectedCategories.name for ...

performing functions concurrently within angularjs

I am currently utilizing angularjs 1.0 within my application. There is a dropdown on my cshtml page <select tabindex="2" id="Employee" ng-model="models.SelectedEmployee" ng-change="changeEmployee()" disabled="disabled" class="Answer" size="6"> < ...

Getting the hang of AngularJS nested controllers: Accessing and utilizing external controller functions

I'm currently working through a programming exercise from a book and I am unsure if I have made an error. I have two controllers in my code, both containing a function with the same name: app.controller('externalController', ['$scope&a ...

Utilizing next-redux-wrapper within the getServerSideProps function in Next.js allows for seamless

When trying to call an action function in getServerSideProps using TypeScript, I encountered some challenges. In JavaScript, it is straightforward: import { wrapper } from "Redux/store"; import { getVideo } from "Redux/Actions/videoAction&qu ...

Angular Material Toolbar Experiencing Color Distortion

To see the issue in action, check out this CodePen: An ongoing problem I've encountered with Angular Material involves distorted colors on the toolbar. The edges of the toolbar display one shade of green, while the middle shows a different shade. Tak ...