Paul Cavacas
Paul Cavacas

Reputation: 4454

AngularJS and TypeScript binding not working

I have the following very simple html fragment

<div data-ng-repeat="goal in vm.goals">!!!</div>

Then in the controller I have the following:

    //this.goals = dataService.createStaticGoals();
    dataService.getCurrentTasks()
        .then(function (results: Array<ReadingLog.Models.UserGoal>) {
        this.goals = results;
        });

If I uncomment the first line then everything works and I see the DIVs as I expect, but when I'm going through the data service method I don't see any divs on the page.

The data service is very simple right now, you can see all it is doing the same createStaticGoals method that did work, just wrapped in promise.

getCurrentTasks(): ng.IPromise<Array<ReadingLog.Models.UserGoal>> {
    var promise = this.$q.defer();

    var goals = this.createStaticGoals();

    promise.resolve(goals);

    return promise.promise;
}

Can anybody see what I'm missing, it has to be something simple, but I just can't seem to see it.

Upvotes: 0

Views: 201

Answers (1)

Thibault Sottiaux
Thibault Sottiaux

Reputation: 197

In a function, the value of this depends on how the function is called and in this case it does not refer to your controller. If you really want it to refer to your controller you can use Function.prototype.bind:

dataService.getCurrentTasks()
    .then((function (results: Array<ReadingLog.Models.UserGoal>) {
       this.goals = results;
    }).bind(controller));

You can read more about the this keyword here and here.

Also note that it is cleaner to name the result of this.$q.defer(), deferred:

var deferred = this.$q.defer();

Upvotes: 1

Related Questions