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

时间:2014-10-29 17:08:53

标签: javascript angularjs

我正在尝试将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 个答案:

答案 0 :(得分:1)

潜在方法:

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

2)直接从childCtrl:

中访问父作用域
$scope.$parent.productDetail

3)如果想要从HTML访问

$parent.productDetail

以上假设您希望访问与子范围上的潜在版本明确分开的值(现有代码未显示)。

如果它是子范围,并且子范围(或其间的范围)中没有任何内容被命名为productDetail,并且您没有在具有该名称的子范围中设置原始值,那么您应该能够通过原型继承直接看到这个值(但是列出的三个场景中的任何一个都可能迫使需要通过父级进行引用)。