I'm trying to write down a Controller that pass a var to a Factory in Angularjs.. The following code return (in console) the values, but I'm not been able to load that into my html page.
Just to record, yes, I'm starting in angularjs.
app.js
var myApp = angular.module('myApp',[]);
myApp.factory('eventData', function ($http, $q) {
delete $http.defaults.headers.common['X-Requested-With'];
return {
getEvent: function (id) {
var deferred = $q.defer();
$http({
method: 'GET',
url: 'page' + id
}).
success(function (data, status, headers, config) {
deferred.resolve(data);
}).
error(function (data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
}
};
});
myApp.controller('AngularJSCtrl',
function FeederController($scope, eventData) {
$scope.data = [];
for (var i = 0; i < 10; i++) {
eventData.getEvent(i).then(
function (data) {
$scope.data = data;
console.log($scope.data);
},
function (statusCode) {
console.log(statusCode)
});
}
}
);
page.html
<div ng-controller="AngularJSCtrl">
<div ng-repeat="patient in patients">
<businesscard>{{patient.name}}</businesscard>
</div>
</div>
$httpis already a promise, you don't need to wrap it inside adeferred. secondly, your code loops through 10 events, queues each one of them up, and when the promise is resolved, each promise is replacing the$scope.dataarray with the single object of that promise. therefore,datais no longer an array andng-repeathas nothing to iterate over. also, you should try to keep your examples consistent, and not usedatain your JS andpatientsin your HTML.$scope.data.push(data)instead, though I would say that iterating over 10 promises instead of fetching the data as a single unit from the server is fairly inefficient. also, you are mixing styles again, with the use of.thenin one snippet and the use of the deprecated.successin the other.