2016-03-09 28 views
0

我試圖從工廠返回已過濾的對象。在「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'; 
}); 
+0

'factory.get'返回一個承諾...... – elclanrs

回答

1

做在你的PostDetailController另一種方式:

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

相反的:

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

希望這將工作

+0

完美!謝謝。我意識到我正在回覆一個承諾,無法用語法來解釋它。 – greypiglet