0

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.

2
  • inside the .then(function ... the reference to this is global, not your controller. Commented Jun 28, 2015 at 14:10
  • Thank You very much that was exactly it. If you submit as answer I will accept it. In case anybody else is looking at this I change the then line to the below, so that this would remain the controller. .then((results: Array<ReadingLog.Models.UserGoal>) => { Commented Jun 28, 2015 at 14:18

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

Comments

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.