Utilizing AngularJS and TypeScript for seamless two-way data binding: a guide for synchronizing controller and directive interaction

Seeking to delegate my table with filtering and sorting functions as a directive. To incorporate two-way data binding, I have implemented the following:

public bindToController = {
      cars: "="
};

This setup is necessary because when a car in the table is clicked, a property of that car is modified, requiring the controller where the cars data originates from to be notified.

export class CarsTableDirectiveController implements ng.IComponentController {
    public cars;

    public $onInit() {
        console.log(this.cars);
    }
    constructor() {
        console.log(this.cars);
    }

}


export class CarsTable implements ng.IDirective {

    public restrict: string = "E";
    public scope = {};
    public controller = CarsTableDirectiveController;
    public controllerAs: string = '$ctrl';
    public bindToController = {
        cars: "="
    };

    static instance(): ng.IDirective {
        return new CarsTable();
    }

    template: string = require<string>('./cars-table.html');

}

To implement this, I call it like so:

<projects-table cars="ctrl.cars"></projects-table>

Although the car data appears in the table, the cars variable is always undefined when logged. What could be causing this issue? How can I establish effective two-way data binding for the cars object and utilize the variable cars within CarsTableDirectiveController?

Answer №1

It seems like your code is in good shape, but it appears that the cars may not be available immediately (possibly due to an AJAX call). This means that when both the constructor and $onInit functions are triggered, the cars might not have been loaded yet.

To address this issue, you can utilize the ng-if directive to ensure that the cars exist before creating your directive:

<projects-table ng-if="cars.length" cars="cars"></projects-table>

By implementing this change, you should now be able to view the cars when the $onInit function is executed, although there may still be a delay when the constructor function runs.

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

Exploring the versatility of WebGL and Three.js with multiple materials on a single intricate grid structure

To enhance performance, I optimize by rendering the grid to a single THREE.Geometry() object using this loop: build: function(){ square = new THREE.Geometry(); face = 0; for(r = 0; r < this["rows"]; r++) for(c = 0; c < this["cols"]; c++) ...

Assign the value of an element in an array to a variable using jQuery

https://i.sstatic.net/RtzeT.png In the jQuery variable, I have received an array and now I am looking to store each array value in a different variable. For example, I want to store the Address field in one variable. How can I achieve this? Any suggestion ...

Exclude promises from a type in TypeScript

Here is my TypeScript snippet: async function get_string(){ return "hello" } var the_string = get_string() In the code, the type of the_string is Promise<string> I am interested in removing the Promise from the type of the_string and m ...

Unique phrase: "Personalized text emphasized by a patterned backdrop

I'm facing a challenge and struggling to find a way to highlight text using CSS or jQuery. My goal is to have an image on the left, another one on the right, and a repeated image in between. Since there are some long words involved, I need a dynamic s ...

Sorting table tbody elements created dynamically with JavaScript on an npm webpack application is not possible with jQuery UI

My JS-built table is populated with data from a JSON file fetched after a request. I want to be able to drag and drop these tbodys and update the JSON file accordingly. To handle sorting, I decided to use jquery-ui. While .sortable() works well for drag a ...

Calling a function within another function is not allowed in Typescript

Essentially, I have an Angular Web Page that uploads a file to the server via a POST request, which is then received by my NodeJS app. The issue arises when attempting to retrieve the file path in subirArchivo() and pass it to a function called InsertaPer ...

A guide on organizing an array of objects by a specific property using a separate array

Here is the array I am working with: var arr = [ { count: 27, dataRil: "08/06/21", subCateg: "FISH", }, { count: 22, dataRil: "08/06/21", subCateg: "DOG", }, { count: 28, dat ...

Is there a way to separate a string using two different delimiters?

Here is my code snippet : <template> ... <p v-for="club in clubs">{{club}}</p> ... </template> <script> export default { data: () => ({ clubs: '' }), mounted () { let dataClub = "- ...

Bookmarklet in JavaScript that automatically extracts and displays Meta keywords in a new tab within the browser

I successfully implemented a script that extracts site meta keywords and writes them into the DOM. javascript:(function metaKeywords() { metaCollection = document.getElementsByTagName('meta'); for (i=0;i<metaCollection.length;i++) { nameAttri ...

What are the best techniques for concentrating on a kendo maskedtextbox?

What is the correct way to set focus on the kendo-maskedtextbox in TypeScript after the view has initialized? The information provided in Telerik's example here is lacking in detail. ...

Assigning a value to an input field using jQuery

I'm facing an issue while trying to set the value for an input using jQuery. Essentially, when you click on a link, it redirects you to a different page with a form, and I am attempting to set the value of one of the inputs in that form. Unfortunately ...

Is the order of state variables important in React components?

Upon executing the code below, an error "Cannot read properties of null (reading 'login')" occurs, triggered by reaching the return statement at the end. This error persists despite the presence of checks for the boolean before the return stateme ...

End of ImageButton tag

I am currently working on this code : <div runat="server" class="slide"> <img src="images/picto_detail.gif" onclick='<%# Eval("CampagneRappelId","hideshow(\"details{0}\")")%>' /> <div id='details<%# Eval("C ...

Setting up a route for a WebSocket server in Express: a step-by-step guide

My setup is structured similarly to the following code: const WebSocketServer = require("ws").Server, express = require("express"), http = require("http"), app = express(), server = http.createServer(app); app.post("/login", login); app.g ...

What could be the reason for TypeScript allowing the injection of an invalid type?

I have the following objects and classes that demonstrate dependency injection: abstract class Animal { speak(): void {}; } class Dog implements Animal { speak(): void { console.log('Woof woof'); } } class Cat implements Ani ...

What is the best way to spy on a property being called within a function?

I am facing an issue where the 'offsetWidth' value is undefined and I need to spyOn it. The function getCurrentPage retrieves an element based on the id currentpage. Although spying on getCurrentPage works, I have been unable to declare the offs ...

What is the best location to store common utility functions that will be utilized by various Vue.js components?

Typically, I create functions within the component that will use them. However, I am finding that I need to use a particular function in multiple components now. Currently, I would have to duplicate and paste the function into each component, which is not ...

Switch back and forth between two different function loops by clicking

I have implemented two sets of functions that animate an SVG: one set runs in a vertical loop (Rightscale.verticalUp and Rightscale.verticalDown) and the other in a horizontal loop (Rightscale.horizontalUp or Rightscale.horizontalDown). On clicking the SVG ...

Converting and downloading CSV to XLSX directly from the front end using TypeScript and React

After successfully converting a JSON response to CSV format for download using the function below, I am now looking to achieve the same functionality but with xlsx files on the front end. The current function works well for CSV files and handles Japanese ...

What is the best way to retrieve and showcase data in NextJs version 13 and beyond?

Being new to NextJS, my question may seem trivial but I'd appreciate your patience. Essentially, my goal is to fetch data from a database and display it on the page upon the initial render. To achieve this, I am utilizing the useEffect and useState ho ...