3

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?

2
  • Does item.name bind properly? Commented Aug 12, 2014 at 10:08
  • @JonEgerton, yes, the name displays correctly. There are also no error outputs into the console at all. Commented Aug 12, 2014 at 10:11

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

which line of code did you remove? the angular.extend or the Object.defineProperty? Can you even remove Object.defineProperty while still using typescript?
@djs, I replaced the angular.extend with a proper copy constructor.
0

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.

1 Comment

Yeah, you were just about right! Thank you for your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.