I have an angularjs
service to get my json
data.
// Controller.js file
$scope.data=Events.query();
$scope.getEventtypes = function(){
angular.forEach($scope.data,function(value, key){
var arr = [];
if(key==$scope.month+$scope.year) {
for(var i=0; i<key.length; i++) {
arr.push(value[i].type);
$scope.eventtypes=arr.unique();
}
}
});
};
while trying to access the value[i].type
it throws an error cannot read property type
of undefined. I know it is because of the asynchronous call.
//i want to add success function like this
$http.get('').success(function(data) {
....
});
can anyone help me?? it will be better if u suggest to do something more efficient than this. Thank you
While @Mahbub suggestion is in the right direction (promises make it easier to coordinate asynchronous functions) it is not the only technique. Good, old callbacks will work as well. While promises are arguably more elegant API the bitter truth it that promises API is not supported as part of the $resource
in he current version of AngularJS.
Theory aside, in your particular case you could simply use a callback and be done with it:
$scope.data=Events.query(function(data){
angular.forEach(data,function(value, key){
var arr = [];
if(key==$scope.month+$scope.year) {
for(var i=0; i<key.length; i++) {
arr.push(value[i].type);
$scope.eventtypes=arr.unique();
}
}
});
});
I had a similar answer using the asynchronuous $http service (with jsonp).
Basically you need to:
With a promise:
var promise = service.getHistoricalDataWithQ($scope.symbol, $scope.startDate, $scope.endDate);
promise.then(function(data) {
$scope.items = data;
});
With a callback:
service.getHistoricalDataWithCallback(function (data) {
$scope.items = data;
}, $scope.symbol, $scope.startDate, $scope.endDate);
See answer Angular using $htp and YQL.
See my jsFiddle.
For this to work, $resource needs to return a promise object like $http does. But angular's latest release doesn't support that yet.
Partap's pull was marked "good to merge" which returns a promise of the $resource. https://github.com/angular/angular.js/pull/1547 . You need to change your resource.js file with this https://github.com/partap/angular.js/blob/005e865e5629a241d99c69a18f85fc2bb5abb1bc/src/ngResource/resource.js
So you can use that and re-factor your code like this
Events.query().$q.then(function(response){
$scope.data=response;
....
....
});