Allow HTTP HTTP request, inside a multi-view router (using ui.router)
I am trying to figure out how to allow HTTP ajax to receive calls with multi-view using UI-Router lib for AngularJs.
JS (app.js):
angular
.module("goHenry", ["ui.router"])
.controller("MainCTRL", MainCTRL)
.config(configB);
function MainCTRL($location){
this.nameApp = "goHenry";
}
JS (router.js):
function configB($urlRouterProvider, $stateProvider){
$urlRouterProvider.otherwise("/");
$stateProvider
.state("/",{
url: "/",
templateUrl : "/testingBlock.htm",
controllerAs : "MainCTRL as ctrl"
})
.state("multi",{
url: "/multi",
views: {
"": {
templateUrl: "/multipleView.htm",
controllerAs: "MainCTRL as ctrl"
},
//blocks
"viewA@multi": {
resolve: {
getChildrenNumber: function($http){
//below here I'm simulating some GET answer
return "Some response from an API";
}
},
templateUrl: "/testingBlock.htm",
controllerAs: "MainCTRL as ctrl"
},
"viewB@multi": {
templateUrl: "/app/templates/login.htm",
controller: function($scope){
$scope.nameApp = "nameAppChanged";
//$scope.getChildrenNumber = getChildrenNumber;
}
}
}
});
}
Should / Can I allow the request inside the main view or inside the sub-view? Then how can I use this result in sub-view and / or main / view, I mean in my own controller.
source to share
There is a working plunker
Start with the controllers, for our ViewA and ViewB:
.controller('MainCTRL', ['$scope', 'getChildrenNumber',
function($scope, getChildrenNumber) {
$scope.children = getChildrenNumber;console.log($scope.children)
}])
.controller('ViewBCtrl', ['$scope', 'getChildrenNumber',
function($scope, getChildrenNumber) {
$scope.children = getChildrenNumber;
}])
And they will be properly supplied if we define the state as follows: 'getChildrenNumber'
.state("multi", {
url: "/multi",
views: {
"": {
templateUrl: "multipleView.htm",
controllerAs: "MainCTRL as ctrl"
},
//blocks
"viewA@multi": {
templateUrl: "testingBlock.htm",
controller: "MainCTRL",
controllerAs: "ctrl",
},
"viewB@multi": {
templateUrl: "app/templates/login.htm",
controller: "ViewBCtrl",
controllerAs: "ctrl",
}
},
resolve: {
getChildrenNumber: ['$http', function($http) {
return $http
.get("data.json")
.then(function(response){
console.log(response.data)
return response.data;
})
}]
},
});
As we can see, the resolution has been moved from the definition of level 1) to the definition of level 2). This means that we can query for such allowed values โโin any of the view controllers
Also a little side note: with UI-Router we have to use this notation: controllerAs
"viewA@multi": {
templateUrl: "testingBlock.htm",
controller: "MainCTRL", // controller name
controllerAs: "ctrl", // the AS part - what will be injected into $scope
Check it in action here
source to share