2014-03-29 69 views
0

我是AngularJS的新手,嘗試製作一個MVC應用程序,其中控制器可以連接到多個相同類型的模型。如何將數據異步從模型返回到AngularJS中的控制器

所以:

我創建連接到測試模型的控制來獲取信息異步,如:

function TestController($scope, Test) 
{ 
    $scope.model = {}; 

    $scope.load : function(id) { 
     Test.get($scope, id); 
    } 
} 

模型使用HTTP協議來檢索服務器(JSON)信息。該模型看起來像:

myApp.factory('Test',function($http) { 
    get : function(variable, id) { 
     $http({ 
      url: 'api/load/'+id 
     }).success(function(response) { 
      variable.model = response;  
     }); 
    } 
}); 

有名稱'模型'硬連線到控制器。所以在控制器中沒有辦法加載第二個測試模型,因爲現有的模型會被覆蓋。

如果我改變行:

Test.get($scope, id); 

Test.get($scope.model, id); 

與模式的

 variable = response; 

角停止的魔力。該模型不在控制器中更新。 Javascript中沒有byRef 。

是否有解決方法,以便Model可以在一個Controller中多次使用?

回答

2

那麼,你不需要像這樣調用服務。首先,$ http調用返回可以使用'then'回調處理的promise。所以你可以爲類似的調用添加多個不同的回調。你的情況:

myApp.factory('Test',function($http) { 
    get : function(id) { 
     return $http({ 
      url: 'api/load/'+id 
     }); 
    } 
}); 

而在你的控制器:

function TestController($scope, Test) { 
    $scope.model = {}; 

    $scope.load : function(id) { 
     Test.get(id).then(function(result) { 
      $scope.var1 = result; 
     }); 

     Test.get(id).then(function(result) { 
      $scope.var2 = result; 
     }); 
    } 
} 

另一種方法是這樣做:

myApp.factory('Test',function($http) { 
    get : function(context, variable, id) { 
     return $http({ 
      url: 'api/load/'+id 
     }).success(function(result) { 
      context[variable] = result; 
     }); 
    } 
}); 

而在你的控制器:

function TestController($scope, Test) { 
    $scope.model = {}; 

    $scope.load : function(id) { 
     Test.get($scope, 'var1', id); 
     Test.get($scope, 'var2', id); 
    } 
} 
+0

謝謝那是我一直在尋找的。使其更具可讀性。 – Toxus

相關問題