2016-08-18 100 views
-2

可有人请看看这个代码,并帮助找出原因,我不断收到此错误。我是angularjs的新手(特别是使用服务/工厂功能)。当函数和局部变量在控制器(而不是$ service)中被定义为$ scope变量时,它工作得很好,但是由于这个函数返回的数据是多个其他控制器所需要的,我想要减少代码冗余。遗漏的类型错误:无法调用未定义的方法“推” - Angularjs

app.service('SupportService', function() 
{ 
    var locations = []; //local variable to which other elements should be added 



//function to get data and update the local variable (this.locations) 

this.setLocations = function() 
    { 
     var temp_location = {}; 

     $.ajax 
     ({ 
      type: 'get', 
      url: 'myurl', 
      success: function(response) 
      { 

       for(var i = 0; i < response.length; i++) 
       { 
        temp_location = 
        { 
         id: response[i].id, 
         name: response[i].name 

        }; 
        locations.push(temp_location); //this is where the error is 
       } 
      }, 
      error: function(response) 
      { 

      } 

     }); 
    } 

用于访问来自服务变量的位置的附加功能是

this.getLocations = function() 
    { 
     return locations; 
    } 

,我使用绑定数据如下

app.controller('RSVPController', function($scope,SupportService,AuthService) 
{ 

    $scope.init = function() 
    { 
     SupportService.setLocations(); 
    } 

    $scope.locations = SupportService.getLocations(); 
}); 

控制器和在视图中我有一个调用该控制器的init函数,并将值附加到select如下

<select ng-model="location" ng-options="item.name for item in locations track by item.id" required></select> 

谢谢。

+0

'this'变化。在事件处理程序中,this指的是发生事件的元素。在'$ .ajax'中,'this'成为ajax对象。 – Tushar

+0

将'context:this'添加到您的'$ .ajax'请求中。虽然你确定你应该在'app.service'回调中为'this'添加属性吗? – 2016-08-18 15:19:06

+0

@squint这不会解决问题。这样,'this'将引用事件发生的元素。 – Tushar

回答

0
app.service('SupportService', function() 
{ 
    this.locations = []; //local variable to which other elements should be added 
    var self = this; 

    enter code here 

//function to get data and update the local variable (this.locations) 

this.setLocations = function() 
    { 
     var temp_location = {}; 

     $.ajax 
     ({ 
      type: 'get', 
      url: 'myurl', 
      success: function(response) 
      { 

       for(var i = 0; i < response.length; i++) 
       { 
        temp_location = 
        { 
         id: response[i].id, 
         name: response[i].name 

        }; 
        self.locations.push(temp_location); //this is where the error is 
       } 
      }, 
      error: function(response) 
      { 

      } 

     }); 
    } 
+0

你只需要指出这是正确的,在这里我用自己,检查出来,看到它工作。 –

1

当你使用“这个”,你必须要小心,因为在不同的范围可能指向不同的对象,你可以简单地删除这个放在一个封闭的位置。服务是单身,它会记住。

+0

如果您需要访问位置,只需添加另一个吸气功能 –

+0

谢谢。它清理了我的用法“this”后,它工作..但现在我似乎无法得到选择元素的价值意味着使用这些数据。选项在视图上正确显示,但在选择一个值并提交表单后返回'undefined'或'[object] [object]'。这里是如何定义选择“