Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i use json data from external file using angularJS restful service

Tags:

angularjs

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. 
like image 352
JSAddict Avatar asked Dec 13 '12 11:12

JSAddict


1 Answers

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

like image 53
jaime Avatar answered Nov 12 '22 06:11

jaime