Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS binding to Typescript property

I have a class defined in TypeScript that has properties defined as getters and setters:

class Item {
    constructor(name: string) {
        this.name = name;
        this._isSelected = false;
    }

    private _isSelected: boolean;

    public name: string;

    public get isSelected() : boolean {
        return this._isSelected;
    }

    public set isSelected(value: boolean) {
        this._isSelected = value;
        console.log('setter invoked');
    }
}

The scope initialization code is as follows:

$scope.items = [
    new Item('A'),
    new Item('B')
];

And the AngularJS markup is similar to:

<div ng-repeat='item in items'>
    <label>
        <input type='checkbox' ng-model='item.isSelected' /> {{item.name}}
    <label>
</div>

The setter is never invoked - no output to the console and no breakpoint hit. Why?

I'm using the latest AngularJS (1.3.0-beta17). Tried using ng-model-options with getterSetter: true, but looks like it requires a special syntax where one function is both getter and setter at the same time, which is not TypeScript-friendly.

UPDATE: defining an anonymous object with get and set works. Maybe this has something to do with TypeScript defining class properties on the prototype instead of the object itself?

like image 659
Impworks Avatar asked Mar 12 '26 17:03

Impworks


1 Answers

I found the reason why it didn't work. My mistake!

The scope initialization code was actually copying objects from another place using angular.extend, and most likely it doesn't account for properties defined using Object.defineProperty. Removing this line fixed the error.

like image 55
Impworks Avatar answered Mar 15 '26 05:03

Impworks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!