2016-08-18 101 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]'。這裏是如何定義選擇「