[英]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.