I'm trying to figure out how resolve http ajax get 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 resolve the request inside the main view or inside the sub-view? Then, how can I use that result in a sub-view and/or in the main/view, I mean in their own controller.
There is a working plunker
Let's start with 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 provided with 'getChildrenNumber', if we define state like this:
.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 - resolve was moved from the 1) view level defintion into 2) state level definition. That means, that we can ask for such resolved values in any of the views' controller
Also small note, with UI-Router we should use this controllerAs notation:
"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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With