Coded Container
Coded Container

Reputation: 863

How to return a function into a scoped variable?

I am trying to use a factory that I can assign to a scoped angular variable. However, whenever I attemp to attach this and use console.log to return this variable I am am returned with the function as text and not as a value. Is there a way I can get this fixed?

========== JS ==========

 annApp.factory('rssFeed', function()
  {
    return function()
    {
      var events = [];
       $.get('xmlfile',
       function(xml)
    {
    var json = $.xml2json(xml); 
    jsonb = JSON.stringify(json, undefined, 3 );
   // var events = []; 
      var description = json['#document']['rss']['channel']['item']['description'];
      var title = json['#document']['rss']['channel']['item']['title'];
      var date = json['#document']['rss']['channel']['item']['pubDate'];
      events.push({'title': title, 'description':description, 'date': date});   
      return events;
   });
   return events; 
 }

annApp.controller('calendar', ['$scope', 'rssFeed', function($scope, rssFeed){
  $scope.events = rssFeed;
  console.log($scope.events);
}]);

Upvotes: 1

Views: 90

Answers (1)

JstnPwll
JstnPwll

Reputation: 8695

If you're trying to print out the reference to the function itself, then what you have is correct (other than the syntax error mentioned by DenimChicken):

annApp.factory('rssFeed', function(){
    return function(){
        var events = [];
        $.get('xmlfile', function(xml){
            var json = $.xml2json(xml); 
            jsonb = JSON.stringify(json, undefined, 3 );
            var description = json['#document']['rss']['channel']['item']['description'];
            var title = json['#document']['rss']['channel']['item']['title'];
            var date = json['#document']['rss']['channel']['item']['pubDate'];
            events.push({'title': title, 'description':description, 'date': date});   
        });
        return events; 
    };
}); // <-- added this

If you're trying to print out the return value from the function, then you need to call the function by putting parentheses after the name:

console.log($scope.events());

However, since $.get is asynchronous, you should either pass in a callback and call it when the request is complete, or use promises.

Upvotes: 1

Related Questions