2015-05-08 80 views
-1

我有我的父母和孩子控制器中的HTTP請求:

父控制器

//Product is a $resource object that return http request as a promise. 
Product.getItem() 
    .then(function(items) { 
     //assign to the scope 
     $scope.items = items 
}) 

兒童控制器

console.log($scope.items) <---get undefined. 

我知道它是未定義的,因爲當頁面第一次加載時HTTP請求還沒有被創建,但我不確定h解決子控制器中的承諾。

+0

使用你究竟是什麼想做?你想添加一個監聽器來查看它何時會被加載,或者你希望能夠在你的頁面加載之前加載它嗎? –

+0

我想添加一個偵聽器來查看數據何時加載 – FlyingCat

+0

@PatrickEvans我不能,因爲我想在其他子控制器中使用返回數據。我需要在父級請求不同的子控制器 – FlyingCat

回答

3

的Theres兩種方法可以解決這個

可以使用監聽器

function checkInit(scopeName, cb){ 
    var listener = $scope.$watch(scopeName, function(new, old){ 
     if (typeof new !== 'undefined'){ 
      cb(); 
      listener(); //deregister event listener 
     } 
    }) 
} 

繼承人一個小功能,並使用它

checkInit('items', function(){ 
    //whatever you like 
}); 

方法2 - 推薦$ http服務

您可以使用承諾的風格有點像這個東西你的父母

$scope.items = Product.getItem(); 

這將返回一個承諾,你可以在任何你的父母或子女或兩個這樣

$scope.items.then(function(response){ 
    //whatever you like 
}) 
+0

在你的方法2中,有沒有辦法檢測父控制器中的promise是否返回錯誤? +1 – FlyingCat

+0

@FlyingCat,只需設置一個失敗回調項:'$ scope.items = Product.getItem()。fail(failCallbackFunctionHere);' –

+0

甜。非常感謝! – FlyingCat