繁体   English   中英

在我的情况下,如何传递http请求结果?

[英]How to pass a http request result in my case?

我正在尝试将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的请求结果,但是不确定如何将其传递给我的子控制器。 有人可以帮我吗?

谢谢!

可能的方法:

1)也将myFactory注入子控制器。

2)直接从childCtrl内访问父作用域:

$scope.$parent.productDetail

3)如果要从HTML访问

$parent.productDetail

上面假设您要访问的值与子范围内的潜在版本特别分开(现有代码未显示该值)。

如果这是一个子作用域,并且该子作用域(或介于两者之间的作用域)中的任何内容都没有命名为productDetail,并且您没有在该子作用域中设置具有该名称的原始值,那么您应该能够直接看到该值通过原型继承(但列出的三个方案中的任何一个都可能需要通过父级进行引用)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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