2014-10-29 59 views
0

我想要獲取http請求結果給我的子控制器。如何在我的情況下傳遞http請求結果?

我有類似

<div ng-controller = "parentCtrl"> 
    <button ng-click="callApi()">click me</button> 

    <div ng-controller = "childCtrl"> 
     <div>{{productDetail}}</div> 
    </div> 
</div> 

angular.module('App').controller('parentCtrl', ['$scope','myFactory', 
    function($scope, myFactory) { 
     $scope.callApi = function() { 
      myFactory.request(id) 
       .then(function(data) { 
        $scope.productDetail = data 
        //do something in parent controller here.... 
       }) 

     } 
    } 
]); 

angular.module('App').controller('childCtrl', ['$scope', 
    function($scope) { 
     //I am not sure how to get the productDetail data here since it's a http request call. 
    } 
]); 



angular.module('App').factory('myFactory', function($http) { 
    var service = {}; 

    service.request = function(id) { 
     return createProduct(id) 
      .then(function(obj) { 
       productID = obj.data.id; 
       return setProductDetail(productID) 
      }) 
      .then(getDetail) 
      .then(function(productDetail) {    
       return productDetail.data 
      })   
    } 
    var createProduct = function(id) { 
     return $http.post('/api/product/create', id) 
    } 

    var setProductDetail = function(id) { 
     return $http.post('/api/product/setDetail', id) 
    } 

    var getDetail = function() { 
     return $http.get('/api/product/getDetail') 
    } 

    return service; 
}); 

我能夠獲得請求的結果我parentCtrl但我不知道如何將它傳遞給我的孩子控制器。任何人都可以幫助我嗎?

謝謝!

+0

'childCtrl'在api調用解析並且'parentCtrl'設置了作用域變量後自動在它的範圍中。 – Absor 2014-10-29 17:14:20

回答

1

電位接近:

1)注入myFactory到子控制器也是如此。

2)直接從內childCtrl訪問父範圍:

$scope.$parent.productDetail 

3)如果從HTML想要訪問

$parent.productDetail 

以上假設您想要訪問該值具體地爲一個單獨的子範圍上的潛在版本(現有代碼未顯示)。

如果它是一個子範圍,並且子範圍(或範圍之間)沒有任何內容被命名爲productDetail,並且您沒有在具有該名稱的子範圍中設置原始值,那麼您應該能夠直接通過原型繼承來看價值(但是列出的三種情況中的任何一種都可能迫使需要通過父代進行引用)。

+0

感謝Mike,但$ scope。$ parent.productDetail和$ parent.produtDetail在頁面第一次加載時將是未定義的,因爲它們是http請求調用。你的第一種方法是可行的,但我覺得在不同的範圍內提出同樣的請求是多餘的+1雖然 – BonJon 2014-10-29 17:33:09

+0

你想要什麼樣的行爲?很顯然,直到解決問題纔有價值。您可以設置$ scope.productDetail =「」(或者在callApi()被觸發並且http呼叫解析之前要顯示的任何其他默認值)。同樣,這個值可用於所有子範圍,並且當promise解析並且productDetail在父控制器中設置時,Angular會自動更新此值。 – Mike 2014-10-29 17:45:29

+0

看看這個Plnkr:http://plnkr.co/edit/QXBPkqOfqdGmV6B69Ju6?p=preview。我只是設置了productDetail值而不是進行http調用,但除此之外,我認爲這實際上就是您編寫的代碼。我做了一個默認值的版本,另一個沒有。你期望/不想要的行爲是什麼?調用callApi()之前應該在子範圍中顯示哪些內容? – Mike 2014-10-29 17:57:08

相關問題