如何在 Angularjs 中回调控制器的方法$http.get().success()



我有这段代码,它运行良好:

var app = angular.module("resources", []);
    app.service("resourceService", function ($http) {
        return {
            GetAll: function (callBack) {
                $http.get("api/Resource/Get").success(function (data) {
                    callBack(data); 
                })
            }
        }
    });
app.controller("resourcesCtrl", function ($scope, resourceService) {
        $scope.resourceList = [];
        resourceService.GetAll(function (data) { $scope.resourceList = data; });
    });

在早期版本的 angularjs 中使用"Controller as"语法,您可以将$scope替换为 this 。 如果我这样做,我的控制器会像:

app.controller("resourcesCtrl", function (resourceService) {
    this.resourceList = [];
    this.setResourceList = function(data){
        this.resourceList = data;
    };
    resourceService.GetAll(this.setResourceList);
});

我添加了setResourceList,以将其称为控制器的方法,以便使用this访问控制器上下文。但是现在,当setResourceList方法作为回调函数运行时,thiswindow的(因为我有一个函数调用,而不是方法调用),所以this.resourceList是未定义的。我正在寻找解决问题的任何解决方案,我认为问题的根源是用this替换$scope.当控制器的属性未使用 $scope 定义时,有没有办法访问它们?

使用闭包来捕获this的值。

app.controller("resourcesCtrl", function (resourceService) {
    var that = this;
    this.resourceList = [];
    this.setResourceList = function(data){
        that.resourceList = data;
    };
    resourceService.GetAll(this.setResourceList);
});

最新更新