6

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. 

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

I tried this, it was not working. i just changed the name '$scope.events' to '$scope.eve' it is working now. Thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.