我正在尝试使用UI-Router lib为AngularJs解决http ajax如何使用多视图获取调用。
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;
}
}
}
});
}
应该/我可以解决主视图内或子视图内的请求吗?然后,我如何在子视图和/或主/视图中使用该结果,我的意思是在他们自己的控制器中。
答案 0 :(得分:3)
让我们从ViewA和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;
}])
如果我们像这样定义状态,那么他们将正确地提供 '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;
})
}]
},
});
正如我们所看到的 - 解决方案已从1)视图级别定义转移到2)状态级别定义。这意味着,我们可以在任何视图的控制器
中请求这样的已解析值另外小编,使用UI-Router我们应该使用 controllerAs
表示法:
"viewA@multi": {
templateUrl: "testingBlock.htm",
controller: "MainCTRL", // controller name
controllerAs: "ctrl", // the AS part - what will be injected into $scope