Obtain a controller's reference from a callback by utilizing TypeScript

Implementing a simple controller that utilizes a directive/component and passes a function as binding. However, when the function is called, there is no reference available to access any of the controller class services.

Within the "public onTileClicked" function in my controller, specifically, there is no access to the tileService.

This scenario can be observed in the following Controller js:

namespace app.dashboard {
    'use strict';

    export class DashboardController {
        static $inject:Array<string> = ['$q', 'logger', 'tileService'];

        constructor(private $q:ng.IQService,
                    private tileService:TileService) {
        }

        public tiles:Array<ITile> = [];

        public onTileClicked(tile:ITile) {                
            this.tileService.getTiles(tile.ID) // No access to tileService
                .then((data)=> {
                    this.tiles = data; // Won't have access to this.tiles
                })
        }
    }

    angular
        .module('app.dashboard')
        .controller('DashboardController', DashboardController);
}

The corresponding Controller html looks like this:

<div class="tiles-container">
    <tile-component ng-repeat="tile in DashboardCtrl.tiles" tile="tile"
                    on-tile-clicked="DashboardCtrl.onTileClicked">
    </tile-component>
</div>

In the Directive js file:

class TileComponent {
    tile:ITile;
    onTileClicked:Function;

   
    constructor() {
    }

    tileClicked() {
        this.onTileClicked()(this.tile);
    }
}

angular.module('app.dashboard')
.component('tileComponent', {
    templateUrl: 'app/dashboard/directives/tile.html',
    controller: TileComponent,
    controllerAs: 'tileCtrl',
    bindings: {
        tile: '<',
        onTileClicked: "&"
    }
});

Finally, the "onTileClicked" functionality in js:

DashboardController.prototype.onTileClicked = function (tile) {
    var _this = this;
    this.tileService.getTiles(tile.ID)
        .then(function (tiles) {
        _this.tiles = tiles;
    });
};

Answer №1

The way you have linked the function in your HTML is incorrect. You forgot to include the parentheses :

<tile-component ng-repeat="tile in DashboardCtrl.tiles" tile="tile"
                on-tile-clicked="DashboardCtrl.onTileClicked()"> <!-- MAKE SURE TO ADD PARENTHESES -->
</tile-component>

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

"Utilizing ng-select with ng-model: A Step-by-Step Guide

Currently, I am working on a code that involves using ng-repeat to loop through options. My goal is to utilize ng-select to choose a value based on a specific condition. However, according to the AngularJS documentation: ngSelected does not interact wit ...

Can Cell be rendered into a targeted element?

Can a Cell from CellJS be rendered into a specific HTML element? For example, including a Cell alongside some static HTML that is not managed by cell. Or having two separate Cell apps on a single page. <!DOCTYPE html> <html> <header> ...

Utilizing the js-yaml library to parse a YAML document

Currently, I'm utilizing js-yaml to analyze and extract the data from a yaml file in node js. The yaml file consists of key-value pairs, with some keys having values formatted like this: key : {{ val1 }} {{ val2 }} However, the parsing process enco ...

Is it possible to return an array of middleware from one middleware to another in Express JS?

Looking to display shop information through a route. The route setup is as follows: router.param('userId',getUserById) router.get("/store/:storeName/:userId?",isAuthenticated,getStoreDetail) My goal is to send different responses based ...

Integrating new components into JSON data

I started by creating a JSON document in my code using the following syntax: let jsonData = []; To populate this document, I utilized the '.push()' method to add elements in this manner: jsonData.push({type: "example", value: "123"}); Eventua ...

Why isn't Sequence.js Slider automatically playing?

Issue: The sequence.js slider I implemented is not animating. Despite adding the following options: animateCanvas: true, fadeStepWhenSkipped: false, autoPlay: true, autoPlayInterval, 2000 It still does not work. Is there something essential t ...

Unable to successfully reset the validity status to true

After implementing server-side validation using the OnBlur event in a form, I encountered an issue where setting the validity of a field to false does not remove the error messages even after setting it back to true. I expected $setValidity true to clear e ...

Using JQuery to Iterate Through All Form Inputs

I am attempting to retrieve the values of all input fields from a form using JQuery and store them in an array to be sent via AJAX with a GET request. My initial approach did not yield the desired results: function gatherFormData(){ $('#formId i ...

What is the best way to convert this JavaScript iteration function into jQuery?

I recently encountered an issue with my JavaScript function that returns a list of elements with the class ".youtube", loops through them, and calls another function. The JavaScript logic is flawless, but I wanted to convert it into jQuery for better reada ...

Tips for setting up Craigslist email forwarding through Node.js (receiving emails to a dynamically generated email address and redirecting them)

After extensive searching, I only came across this Stack Overflow post about Email Forwarding like Craigslist in Rails: Email Forwarding like Craigslist - Rails I spent a significant amount of time googling, but couldn't find any solutions using Node ...

What is causing the failure of the serial reader in NodeJS?

I have successfully installed serialport using npm, but for some reason it is encountering connection issues. $ ls /dev/tty.* /dev/tty.Bluetooth-Incoming-Port /dev/tty.usbserial-AI0255BX $ cat /var/tmp/test.js var SerialPort = require('serialport ...

Tricks for preventing axios from caching in GET requests

I am utilizing axios in my React-Native application Firstly, I set up the headers function setupHeaders() { // After testing all three lines below, none of them worked axios.defaults.headers.common["Pragma"] = "no-cache"; axios.defaults.heade ...

What is the best way to access the rendered child components within a parent component?

I am seeking a way to retrieve only the visible child components within a parent component. Below is my unsuccessful pseudo-code attempt: parent.component.html <parent (click)="changeVisibility()"> <child *ngIf="visible1"></child> ...

What is the best way to pass an array to a child component in React?

I am having an issue where only the first element of inputArrival and inputBurst is being sent to the child component Barchart.js, instead of all elements. My goal is for the data to be instantly reflected as it is entered into Entrytable.js. EntryTable.js ...

React: Remove a particular row from the table

I am currently working on a project that involves building a table component. Each row in this table is also a separate component. class FormulaBuilder extends Component { constructor(props) { super(props); this.state = ...

Exploring AngularJS Navigation in Windows 8 App Store Applications

Hello, I recently started learning about developing Windows Store apps. I found a way to incorporate AngularJS into my Windows 8 store app by making some adjustments in the AngularJS library. However, I'm now struggling with implementing AngularJS rou ...

What is the best way to retain data after clicking a button?

I am facing an issue where I need to figure out how to add information to a new page when a button is clicked. For example, let's say I have an "add to cart" button and upon clicking it, I want to store some data. How can I achieve this functionality? ...

"Sticky Top Button That Stays in Place When Scrolling | Innovative CSS & jQuery

I've been inspired by the "Proceed to checkout" button on amazon.com and I want to recreate it. However, I'm facing a challenge as their website is not responsive and I can't find a way to view a device user agent in Chrome. To see what I&ap ...

The information returned to the callback function in Angular comes back null

In my Node.js application, I have set up an endpoint like this: usersRoute.get('/get', function(req, res) { //If no date was passed in - just use today's date var date = req.query.date || dateFormat(new Date(), 'yyyy-mm-dd&ap ...

The dynamically rendered component cannot be assigned to the type 'IntrinsicAttributes & ContentOutlineProps & ContentBrainstormProps'

I am facing an issue on my page where a <SideBar /> component is causing a Typescript error with the setActivePage hook. The error message points to a specific line in my code: const Content: (({ question_blocks, }: ContentBrainstormProps) => JSX. ...