这是我的 UI-Router 配置。我有一个主要产品 View 和下面的两个嵌套状态。我希望每个嵌套 View 都有自己的 Controller ,但我也希望能够从父 Controller (productsCtrl) 继承一些基本信息。我的假设是我可以从 productShowCtrl 访问 productsCtrl,但它一直返回为未定义。 productsCtrl和productShowCtrl默认没有父子关系吗?
var myProducts = angular.module('Products', [
'ProductsShow'
])
.config(function($stateProvider, $urlRouterProvider){
$stateProvider.state('store.products', {
url: '/products',
views: {
'subhead@': {
templateUrl:'products/list/subhead.tmpl.html'
},
'content@': {
templateUrl:'products/list/list.tmpl.html',
controller: 'ProductsCtrl as productsCtrl'
}
}
})
.state('store.products.create', {
url: '/create',
views: {
'subhead@': {
templateUrl: 'products/create/subhead.tmpl.html'
},
'content@': {
templateUrl: 'products/create/create.tmpl.html'
}
}
})
.state('store.products.show', {
url: '/:productId',
views: {
'subhead@': {
templateUrl: 'products/show/subhead.tmpl.html'
},
'content@': {
templateUrl: 'products/create/create.tmpl.html',
controller: 'ProductShowCtrl as productShowCtrl',
}
}
});
});
ProductsCtrl(主要产品 View ):
myProducts.controller('ProductsCtrl', function($stateParams) {
var productsCtrl = this;
productsCtrl.parentTest = "PARENT";
});
ProductsShowCtrl(用于 subview ):
angular.module('ProductsShow', [])
.controller('ProductShowCtrl', function($stateParams) {
var productShowCtrl = this;
productShowCtrl.childTest = "CHILD";
console.log('parent: ', productsCtrl.parentTest);
});
我无法从 ProductShowCtrl
访问 productsCtrl.parentTest
。我怎样才能访问它?
最佳答案
有相关问答:
- > ui router - nested views with shared controller
- > How do I share $scope data between states in angularjs ui-router?
此处使用 controllerAs
的示例可能是这样的:
状态定义:
.state("main", {
controller:'mainController',
controllerAs:'mainCtrl',
url:"/main",
templateUrl: "main_init.html"
})
.state("main.1", {
controller:'childController',
parent: 'main',
url:"/1",
templateUrl: 'form_1.html'
})
.state("main.2", {
controller:'childController',
parent: 'main',
url: "/2",
templateUrl: 'form_2.html'
})
主 Controller 将定义模型
:
app.controller('mainController', function ($scope) {
var Model = {Name : "xxx"}; // controller property Model
})
在 form_1 或 form_2 中,我们可以使用 controllerAs
语法访问该模型:
<div>
<h5>Child state FORM 2</h5>
<pre>{{mainCtrl.Model}}</pre>
Change the value in a child state FROM 2
<input ng-model="mainCtrl.Model.Name" />
</div>
其中 mainCtrl.Model
表示对父 Controller 的引用(在我们及其 $scope 内)
查一下here
关于javascript - Angular UI 路由器 - 嵌套 View 的 Controller 是否自动成为父 View Controller 的子级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32491555/