Reputation: 2818
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?
Upvotes: 3
Views: 2845
Reputation: 2818
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.
Upvotes: 3
Reputation: 41539
I suspect its not exactly AngularJS that's the problem here, so much as just the casting/deserialization: I'm not sure you can cast Json objects to Typescript classes without some sort of cloning/copying in the middle.
In my case I've interfaces defined that match the incoming Json, and casting to those work perfectly, but doing this you obviously don't get the setter functionality in the middle.
See this question, which sort of covers this area, and some of the options you've got.
Upvotes: 0