javascript - AngularJS 和 TypeScript 绑定(bind)不起作用

标签 javascript angularjs

我有以下非常简单的 html 片段

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

然后在 Controller 中我有以下内容:

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

如果我取消注释第一行,那么一切都会正常,并且我会按照预期看到 DIV,但是当我执行数据服务方法时,我在页面上看不到任何 div。

数据服务现在非常简单,您可以看到它正在执行相同的 createStaticGoals 方法,该方法确实有效,只是包装在 Promise 中。

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

    var goals = this.createStaticGoals();

    promise.resolve(goals);

    return promise.promise;
}

任何人都可以看到我错过了什么,它必须是简单的东西,但我似乎看不到它。

最佳答案

在函数中,this 的值取决于函数的调用方式,在这种情况下,它不引用您的 Controller 。如果您确实希望它引用您的 Controller ,您可以使用 Function.prototype.bind :

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

您可以阅读有关 this 关键字的更多信息 herehere .

另请注意,将 this.$q.defer(), deferred 的结果命名更清晰:

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

关于javascript - AngularJS 和 TypeScript 绑定(bind)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31100687/

相关文章:

angularjs - 是否可以使用 $rootScope 作为存储在 Angular 1 中实现类似 Redux 的架构?

javascript - AngularJS $location.path 循环回根

javascript - Google Chrome - 用于禁用超链接提交的 iframe 沙箱不起作用

javascript - 使用jquery从组中获取组成员

javascript - 何时调用后端,何时本地存储(angularjs)

angularjs - 如何重新加载 ionic View ?

javascript - 如何在javascript中获取动态id

javascript - angular-ui-layout - 调整大小无法在 iframe 中正常工作

javascript - 我如何 bower 安装 Raphael.js?

javascript - 如何使 Angular 子范围刷新?