我得到了一个main.html
文件,其中有一个根据$scope.parameter
的状态可见/隐藏的section
。这个main.html
用于我的两条路线,一条是"主"路线,另一条是子路线。这个样子,
.state('medications', {
url: '/medications',
templateUrl: '/partials/home.html',
controller: 'mainController',
resolve: {
postPromise: ['medicationservice', function(medicationservice) {
return medicationservice.getAll();
}]
}
})
.state('medications.add', {
url: '/add',
templateUrl: '/partials/home.html',
controller: 'mainController'
})
在这种情况下,我想做的是设置$scope.parameter
来显示这个section
。我看过这个例子,但我不知道如何设置它应该使用的控制器。
$stateProvider.state('contacts', {
template: '<h1>{{title}}</h1>',
controller: function($scope){
$scope.title = 'My Contacts';
}
})
如何在明确设置控制器名称的情况下设置参数?
选项1:
使其成为stateParams
(推荐):
.state('medications', {
params: {showSection: false},
//...
.state('medications.add', {
params: {showSection: true},
//...
并将mainController
中的$scope
变量设置为$stateParam
:
$scope.$watch($stateParams.showSection, function(){
$scope.parameter = $stateParams.showSection;
}, true);
选项2:
观看$stateChangeStart
事件并根据toState
:更改$scope
变量
$scope.$on('$stateChangeStart',
function(event, toState, toParams, fromState, fromParams){
$scope.parameter = toState === 'medications' ? false : true;
})
使用$state的"data"对象:
.state('medications.add', {
url: '/add',
templateUrl: '/partials/home.html',
controller: 'mainController',
data: { myParameter: 'true' }
})
然后,在控制器中,您可以使用$state服务访问数据。将数据分配到控制器的范围,你就可以开始了:
angular.module('myapp').controller('myController',function($scope,$state){
$scope.myParameter = $state.data.myParameter;
});