I am developing an application. In that i am retrieving the json data from an
external file using $http.get() method it worked fine. Now i am trying to use angular
restful services. it is working fine in filters, but when i use it in controller it is
displaying undefined.
//Service.js File
angular.module('calenderServices', ['ngResource']).
factory('Events', function($resource){
return $resource('/EventCalender/:File.json', {}, {
query: {method:'GET', params:{File:'events'}, isArray:true}
});
});
//This is my app Module
angular.module('calender', ['eventFilters','highlight','event','calenderServices']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('', {templateUrl: 'template.html', controller: MonthCtrl}).
otherwise({redirectTo: '/invalid'});
}]);
//This is my filter.js
angular.module('eventFilters', ['calenderServices']).filter('compare', function(Events) {
var events=Events.query();
alert(events[0].name); //it is displaying the name "Milestone1" });
//This is my controller.
function MonthCtrl($scope, Events){
var events=Events.query();
alert(events[0].name); //it is displaying undefined
}
//whenever i try to use the variable 'events' in controller, it is displaying undefined or null. But in filter it is working fine.
The following wont work because ngResource makes an asynchronous http request.
var events=Events.query();
alert(events[0].name); // <--- here events is an empty array
Usually all you need to do is the following and your data will be available to render in your view
$scope.events = Events.query()
It looks like a synchronous operation, but it isn't. This is angular's zen at work. You can learn the details from the docs.
To further process the data, you could also pass pass a success callback to the get
method
Events.query(function(events){
// here you have access to the first event's name
console.log(events[0].name);
});
here's a working example: http://plnkr.co/edit/NDZ2JWjMUoUvtzEuRUho?p=preview
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With