$ scope无法使用Angularjs中的$ http.get从工厂获取数据

时间:2016-06-25 03:16:13

标签: angularjs asynchronous factory httpservice

<script>
var app = angular.module('myApp', ['ngMaterial']);

app.factory('factoryProvider', function ($http, $q) {
    var facObj = {};
    facObj.getLastWorkplace = $http.get('plugins/wcf-service/ServiceProvider.svc/getLastWorkPlacesJSON')
        .then(function (response) {
            return response.data;
        });
    return facObj;
});

app.controller('dashboardController', function ($scope, factoryProvider) {

    factoryProvider.getLastWorkplace.then(function (successResponse) {
        $scope.wp = successResponse;
        console.log('inside');
        console.log($scope.wp); // Return an object that I want
    });
    console.log('outside');
    console.log($scope.wp); // $scope.wp is empty
});

外部控制台日志首先运行,控制台日志内部是第二个。问题是$ scope.wp只能获取getLastWorkplace回调函数中的数据,并且无法将数据绑定到ng-model(使用wp.property)。怎么解决? 感谢您的阅读

1 个答案:

答案 0 :(得分:1)

您要分配$scope.wp两次,最终分配是getLastWorkplace来电的返回值(您没有返回任何内容。)

将其更改为此...

factoryProvider.getLastWorkplace.then(function (successResponse) {
    $scope.wp = successResponse;
});

...或

$scope.wp = factoryProvider.getLastWorkplace;

但不是两者。