2014-10-29 71 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

相关问题