2015-06-18 82 views
-2

如何將我的devices屬性設置爲從/store.aspx/GetDevices返回的數據。使用this.devices不起作用。參考控制器屬性與控制器作爲語法

var app = angular.module("storeApp", []); 
app.controller("storeController", ['$http', function ($http) { 

    this.devices = hardcodeddevices; 
    $http.post("/store.aspx/GetDevices", {}) 
     .success(function (data) { 
      //this.devices = JSON.parse(data.d); 
     }); 

}]); 

var hardcodeddevices = [... 
+0

像這樣'函數(data){ //this.devices = JSON.parse(data.d); } .bind(this)' – Grundy

+2

或將_this_賦值給某個變量並使用它 – Grundy

+0

[將正確的「this」上下文傳遞給setTimeout回調?](http://stackoverflow.com/questions/2130241/pass-correct -this-context-to-settimeout-callback) – Grundy

回答

0

在你成功的回調函數,this意味着成功回調function.You可以分配this給一個變量像self

var app = angular.module("storeApp", []); 
app.controller("storeController", ['$http', function ($http) { 
    var self = this; 
    self.devices = hardcodeddevices; 
    $http.post("/store.aspx/GetDevices", {}) 
     .success(function (data) { 
      self.devices = JSON.parse(data.d); 
     }); 

}]); 

var hardcodeddevices = [... 
+0

你錯了:在成功回調函數中,'this'的意思是'$ http'對象 – Grundy

+1

可能正確的方法是使用角度服務處理從服務器返回的數據並使用DI在控制器中獲取該數據,並且可以指定到'this'或$ scope, –