AngularJS : Returning .then() response to controller property -
i'm using factory retrieve data using $http , controlleras capabilities inject view. without use of $scope, having issues returning $http response data property in controller.
my factory
myapp.factory('topics', function ($http, $q) { var service = {}, _error = 'oh no! went wrong. please check later.'; service.gettopics = function () { var deferred = $q.defer(); $http.get(_url).success(function (resp) { deferred.resolve(resp); }).error (function () { deferred.reject(_error); }); return deferred.promise; } return service; }); my controller
myapp.controller('topicsctrl', function (topics) { this.topics = (function () { return topics.gettopics().then(function (resp) { console.log(resp); return resp; }); })(); } my view
<h1>{{ top.topics }}</h1> like said i'm using controlleras in route configured top. console.log in controller logs i'm looking value of topics empty when injected view. leaving me {}.
p.s. understand $http abstraction of $q makes me wonder if using $q in example unnecessary.
the following should work:
myapp.controller('topicsctrl', function (topics) { topics.gettopics().then(function (resp) { this.topics = resp; }.bind(this)); }); then access in view via top.topics.
edit: also, you're correct in not needing $q in service. can return $http.get directly:
service.gettopics = function() { return $http.get(_url); };
Comments
Post a Comment