如何将函数返回到作用域变量?

时间:2015-11-13 21:03:25

标签: javascript angularjs

我正在尝试使用可以分配给范围角度变量的工厂。但是,每当我尝试附加它并使用console.log返回此变量时,我将返回函数作为文本而不是值。有没有办法解决这个问题?

========== 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);
}]);

1 个答案:

答案 0 :(得分:1)

如果你试图打印出对函数本身的引用,那么你所拥有的是正确的(除了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

如果您尝试从该函数打印出返回值,则需要在名称后面添加括号来调用该函数:

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

但是,由于$.get是异步的,您应该传入回调并在请求完成时调用它,或者使用promises。