I\'m trying AngularJS for the first time. I\'m getting JSON data from a http-get request using a factory, but the object is returned empty, before the ajax-request is done.<
Using the q promise library means your success function can stay in your service:
app.factory('Data', function ($http, $q) {
return {
ajaxItems: function () {
var deferred = $q.defer();
$http({ method: "POST", url: "/Home/GetSearchResults" })
.success(function (data, status, headers, config) {
deferred.resolve(data);
}).error(function (data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
}
}
});
app.controller('ResultsCtrl', ['$scope', 'Data', function ($scope, Data) {
$scope.get = function () {
$scope.items = Data.ajaxItems();
//the model returns a promise and THEN items
$scope.items.then(function (items) {
$scope.items = items;
}, function (status) {
console.log(status);
});
};
}]);