努力 return 结果从工厂范围

Struggling to return result to scope from factory

我正在尝试 return 来自工厂的过滤对象。在 "return getTheChosen" 点,对象符合预期。我无法将它分配给我的 $scope.postDetail!

感谢任何建议!

app.factory('postsFactory', function ($http) {

    var response = $http.get('http://myjsonendpoint.com/');

    var factory = {};

    factory.list = function () {
        return response;
    };

    factory.get = function (id) {
       var getTheChosen = factory.list().then(function (res) {
            var chosen =  _.find(res.data, {'id': id});
            return chosen;
        });
        return getTheChosen;
    };

    return factory;

});

然后...

app.controller('ThoughtsController', function ($scope, postsFactory) {
    postsFactory.list()
        .then(function (data) {
            $scope.posts = data;
        });
});

然后...

app.controller('PostDetailController', function ($scope, postsFactory, $routeParams) {
    $scope.postDetail = postsFactory.get(parseInt($routeParams.postId));
    $scope.test = 'yep';
});

在你的 PostDetailController 中用另一种方式做:

postsFactory.get(parseInt($routeParams.postId)).then(function(data) {
    $scope.postDetail = data;
});

而不是:

$scope.postDetail = postsFactory.get(parseInt($routeParams.postId));

希望这会奏效