努力将结果从工厂返回到范围

时间:2016-03-09 18:16:03

标签: javascript angularjs lodash

我试图从工厂返回过滤后的对象。在"返回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';
});

1 个答案:

答案 0 :(得分:1)

在PostDetailController中采用另一种方式:

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

而不是:

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

希望这会起作用