且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

AngularJS服务中的变量不是在视图中更新吗?

更新时间:2023-11-14 19:56:58

从服务中返回$ http承诺:

Return the $http promise from the service:

app.service("API", function($http) {
    this.getTasks = function() {
        return $http.get(url);
    };
});

然后在控制器中,从promise中提取数据:

Then in the controller, extract the data from the promise:

app.controller("mainController", function($scope, API) {
    this.$onInit = function () {
        console.log("Initializing app");
        API.getTasks().then(function(response) {
            $scope.tasks = response.data;
        });    
    };
});

有关更多信息,请参见 AngularJS $ http服务API参考.

For more information, see AngularJS $http Service API Reference.