我想与您分享我的方法。有一个working plunker。
让我们有三个区域布局 - 顶部、左侧、主要。这些可能是状态:
$stateProvider
.state('index', {
url: '/',
views: {
'@' : {
templateUrl: 'layout.html',
controller: 'IndexCtrl'
},
'top@index' : { templateUrl: 'top.html',},
'left@index' : { templateUrl: 'left.html',},
'main@index' : { templateUrl: 'main.html',},
},
})
.state('index.list', {
url: '^/:category',
templateUrl: 'list.html',
controller: 'ListCtrl'
})
.state('index.list.detail', {
url: '/:id',
views: {
'detail@index' : {
templateUrl: 'detail.html',
controller: 'DetailCtrl'
},
},
})
索引将创建一个范围,该范围将被继承到每个子状态和大子状态。所以我们可以使用$scope.Model 来保持数据的整合。
这些将是控制器:
.controller('IndexCtrl', ['$scope', function($scope){
$scope.Model = {
categories : ["Music", "Video"],
}
}])
.controller('ListCtrl', ['$scope', '$stateParams', function($scope, $stateParams){
// add items to the model
$scope.Model.items = $stateParams.category === "Music"
? ["Depeche Mode", "Nick Cave"]
: ["Star Wars", "Psycho"]
$scope.$on("$destroy", function() {delete $scope.Model.items; })
}])
.controller('DetailCtrl', ['$scope', '$stateParams', function($scope, $stateParams){
// add item to model
$scope.Model = {
item : $scope.Model.items[$stateParams.id],
}
$scope.$on("$destroy", function() {delete $scope.Model.item; })
}])
这里发生了什么?部分我们使用 $stateParams 来改变状态(category 被传递给 List ... id 进入细节)
所有状态(一直向下)都可以访问$scope.Model 的同一实例(参考)
全部查看here
另外,这里发生的是 $scope 继承的真正用途,在 UI-Router 中是由视图嵌套驱动的。请检查this detailed description