快速简单的答案是使用$ rootScope . $ rootScope可供所有控制器使用,但是应该谨慎使用所有全局变量 .
基本上,如果你在你的两个控制器上使用它来寻找页面x和y
app.controller('login',['$scope','$rootScope', function ($scope,$rootScope) {
$rootScope.foo='bar';
}]);
app.controller('xCtrl',['$scope','$rootScope', function ($scope,$rootScope) {
$scope.lorem=$rootScope.foo;
console.log($scope.lorem); //bar
}]);
app.controller('yCtrl',['$scope','$rootScope', function ($scope,$rootScope) {
$scope.ipsum=$rootScope.foo;
console.log($scope.ipsum); //bar
}]);
然后可以像往常一样在HTML标记中使用它们 .
使用$ rootScope要简单得多,但是如果你想每次都使用路由器来下载id,那么它也是可能的 .
app.config(function($routeProvider){
$routeProvider
.when('/',{
controller: 'indexController',
templateUrl: 'view/index.html'
})
.when('/:id/about',{
controller: 'xCtrl',
templateUrl: 'view/x.html'
})
.otherwise({
redirectTo: '/'
});
});
app.controller('xCtrl',['$scope','$routeParams', function($scope,$routeParams){
$scope.foo=$routeParams.id;
}]);
如果你有更多的页面而不仅仅是/我可以想象这对路由有点棘手 .
您甚至可以将其与根范围耦合,然后将其传递给其他控制器 .
app.controller('xCtrl',['$scope','$rootScope','$routeParams', function($scope,$rootScope,$routeParams){
$rootScope.foo=$routeParams.id;
$scope.lorem=$rootScope.foo;
}]);
--EDIT基于评论 - 我可能需要一些代码来确定你所追求的是什么,但也许这澄清了?
网址:mysite.com/blue/about
app.config(function($routeProvider){
$routeProvider
.when('/',{
controller: 'indexController',
templateUrl: 'view/index.html'
})
.when('/:id/about',{
controller: 'xCtrl',
templateUrl: 'view/x.html'
})
.otherwise({
redirectTo: '/'
});
});
app.controller('xCtrl',['$scope','$routeParams', function($scope,$routeParams){
$scope.theme=$routeParams.id;
}]);
HTML
My theme is {{theme}}.
CSS
.blue
{
background-color: blue;
}
.green
{
background-color: green;
}