我是Angular的新手。
// This is my main controller
app.controller('AppCtrl', ['$rootScope', '$scope', 'cfpLoadingBar', '$http',
function ($rootScope, $scope, cfpLoadingBar, $http) {
cfpLoadingBar.start();
$rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
//stop loading bar on stateChangeSuccess
event.targetScope.$watch("$viewContentLoaded", function () {
// HERE I want to send request to API and on complete do
// 1. Complete loadbar
// 2. Write response to global var and use it from other controller
$http.get(
'/api/',
{}
).then(function (response) {
// Completing loadbar
cfpLoadingBar.complete();
$SOME_GLOBAL_VAR.api = response;
});
});
});
}]);
// Controller 1
app.controller('Ctrl_1', ["$scope", "$http" function ($scope, $http) {
$scope.param = 'get_data_1';
When $SOME_GLOBAL_VAR.api
console.log($SOME_GLOBAL_VAR.api);
}]);
我想对不同的控制器使用一个api请求。 所以我想加载API,当它完成时 - 每个控制器都会渲染他的部分。 现在我无法理解如何听取API加载完成?
答案 0 :(得分:2)
您可以通过以下方式实现此目的
$http.get(
'/api/',
{}
).then(function (response) {
// Completing loadbar
cfpLoadingBar.complete();
$rootScope.$emit("receivedApiUpdate", response);
});
angular.module("my_module")('controller1', ['$rootScope', function($rootScope) {
$rootScope.$on('receivedApiUpdate',function(event, response){
// Do your work
});
}]);
angular.module("my_module")('controller2', ['$rootScope', function($rootScope) {
$rootScope.$on('receivedApiUpdate',function(event, response){
// Do your work
});
}]);
angular.module("my_module")('controller3', ['$rootScope', function($rootScope) {
$rootScope.$on('receivedApiUpdate',function(event, response){
// Do your work
});
}]);
答案 1 :(得分:1)
您可以尝试提供服务并在您的控制器上使用您的服务。