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

The Next JS project fails to compile when a hyperlink is sent to the Link component from an external source

I am encountering an issue with a Menu Item component that pulls its href and label from another component known as NavBar. The strange thing is that it works perfectly fine when running yarn dev, but fails to build. However, when I make a simple change to ...

Is the value of the object in the array already present in another array of objects?

Plunker - http://plnkr.co/edit/jXdwOQR2YLnIWv8j02Yp In my angular project, I am working on a view that displays a list of users in the main container (array-A) and a sidebar with selected users (array-B). The first array (A) contains all users: [{ $$has ...

Tips for Effectively Declaring a Variable with React's useState

How should I correctly specify variable types in useState? In the code below, the value for alert must be either "success","warning", "error", or "info" const [alertValue, setAlertValue] = useState("error" ...

Can you demonstrate how to showcase images stored in an object?

Is there a way to properly display an image from an object in React? I attempted to use the relative path, but it doesn't seem to be working as expected. Here is the output shown on the browser: ./images/avatars/image-maxblagun.png data.json " ...

Adjust the size of an element by utilizing a different element

I'm facing a challenge with this code. I need to dynamically set the width of the "wrap-description" divs to be equal to the width of the corresponding "picture-damage" images plus an additional 20 pixels. Since there will be multiple elements for bot ...

`A brief disruption in loading the visual style of Google Maps`

Using the Ionic Framework, AngularJS, and Google Maps API, I encountered an irritating issue with my mobile app. Every time the map loads, there is a noticeable delay in loading the map style. This delay is particularly problematic as my map style converts ...

A guide on utilizing the useEffect hook to dynamically update a button icon when hovering over it in a React application

Is it possible to change the icon on a button when hovering using useEffect? <Button style={{ backgroundColor: "transparent" }} type="primary" icon={<img src={plusCart} />} onCl ...

The Excel Match function is experiencing issues when used in conjunction with the MS-Graph API

Recently, I've encountered an issue with sending a match-function post request to an Excel workbook using the MS-Graph API. Instead of receiving the value of the first column that contains the lookup value, I'm getting the value from the second c ...

Connect Angular Material by chaining together md-select elements from arrays and array of form inputs

I am encountering a challenge with combining chains in Angular Material. I aim to transition from this linked solution on jsfiddle to using md-select and md-option in Material. How should it function? It's quite simple. Here's the scenario: Se ...

Tips for enhancing the user experience with a speed-optimized framework interface

The perception of a web page's loading time by users may not always align with the actual loading time. Here are various scenarios that can affect how users experience page loading: Users waiting for a blank page to load all at once. Some parts of t ...

Managing AJAX Requests in AngularJS

I am currently developing a Single Page Application where the front end is hosted on one server and the back end is hosted on another. For every add, edit, delete, or fetch operation, I have to make an Ajax request to the Back End. There have been quite ...

Similar to TypeScript's `hasOwnProperty` counterpart

When working with TypeScript objects, is there a way to loop through a dictionary and set properties of another dictionary similar to how it is done in JavaScript? for (let key in dict) { if (obj.hasOwnProperty(key)) { obj[key] = dict[key]; } } If ...

Firebase 3 authentication does not maintain persistent login sessions

I recently upgraded my AngularJS app to use Firebase 3.x and AngularFire 2.x for email and password authentication. I referred to the following documentation for migration: https://firebase.google.com/support/guides/firebase-web https://github.com/fi ...

Fake AxiosInstance. In need of obtaining response in a single test

In my api.ts file import axios from 'axios' export const api = axios.create({ baseURL: 'http://localhost:3333/', }) Within my react-page.spec.tsx file: import React from 'react' import '@testing-library/jest-dom&apo ...

Unable to get Angular ng-click to function properly when used in conjunction with $

I am encountering an issue with triggering a click event in my Angular app using code similar to the example below. Can anyone help me understand why the event is not being triggered? var app = angular.module("myApp", []) app.directive('myTop', ...

XSRF Cookies are failing to attach to the request header when an https iframe is being loaded on an http site

Recently, I successfully implemented XSRF protection on a website using MVC and AngularJS. The secure site can be accessed in two ways: through a direct post or within an iframe. Below is the code snippet: .config(function ($httpProvider) { $h ...

What is the process for converting variadic parameters into a different format for the return value?

I am currently developing a combinations function that generates a cartesian product of input lists. A unique feature I want to include is the ability to support enums as potential lists, with the possibility of expanding to support actual Sets in the futu ...

Using a snapshot test with MenuItem from material-ui is not compatible with Jest

I am facing an issue while trying to perform a snapshot test with jest on a component that utilizes typescript, react, and material-ui. Specifically, the MenuItem component from material-ui is throwing an Invariant Violation: getNodeFromInstance: Invalid a ...

Angular - Unable to access property '$invalid' because it is null

Working on my login page with angular and typescript. Clicking the submit button should trigger the login function in the controller, but if the form is invalid, it should just return. New to typescript, I keep running into an error when trying to add an ...

Unable to configure unit tests for Vue project using Typescript due to TypeError: Unable to destructure property `polyfills` of 'undefined' or 'null'

I've been working on adding unit tests for an existing Vue project that uses Typescript. I followed the guidelines provided by vue-test-utils for using Typescript, but when I ran the test, I encountered an error message stating: TypeError: Cannot d ...