testiguy testiguy - 1 month ago 8
Javascript Question

How to use two-way-databinding between controller and directive using AngularJS and TypeScript

I want to outsource my table with their filter and sort functions as a directive.
Since I want to use two-way-databinding I am doing this:

public bindToController = {
cars: "="
};


This is because when clicking in the table on a car, I am changing a property of this car and I need the controller where
cars
comes from to be aware of this.

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');

}


I am calling it like this:

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


The cars data is shown in the table, but when I log
cars
it's always undefined.
What am I doing wrong? How can I achieve a two-way-databinding of the object
cars
and use the variable
cars
in
CarsTableDirectiveController
?

Answer Source

Your code looks good, which makes me think the cars just aren't available right away (do they come from an AJAX call?). Thus when constructor and $onInit fire, the cars aren't there yet.

You can use ng-if to wait until cars exist to create your directive:

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

Now you should see the cars when $onInit fires (but not necessarily when constructor fires).