简体   繁体   中英

How to pass a http request result in my case?

I am trying to get the http request result to my child controller.

I have something like

<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;
});

I was able to get the request result for my parentCtrl but I am not sure how to pass it to my child controller. Can anyone help me about it?

Thanks!

Potential approaches:

1) Inject myFactory into the child controller as well.

2) Access the parent scope directly from within childCtrl:

$scope.$parent.productDetail

3) If wanting to access from HTML

$parent.productDetail

Above assumes you are wanting to access that value specifically separate from a potential version on the child scope (existing code doesn't show that).

If it's a child scope, and nothing on the child scope (or a scope in between) is named productDetail, and you're not setting a primitive value in the child scope with that name, then you should be able to see the value directly through prototypical inheritance (but any of the three scenarios listed could force the need for a reference through the parent).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM