带有 Angular UI-Router 的动态主体类 [英] Dynamic body class with Angular UI-Router
问题描述
我试图找到一种优雅的方式来拥有 body 标签 的自定义动态类,我可以从 ui-router 配置
轻松设置,如果没有已设置,我可以使用默认选项或不使用.
示例:
routes.js
$stateProvider.state('登录', {网址:/登录",模板:'登录'}).state('注册', {网址:/注册",模板:'注册'})..state('个人资料', {网址:/个人资料",模板:'个人资料'});;
简单的 HTML 标记
<body class=""><!-- 动态类改变--><div ui-view></div></html>
场景:
1 - 访问 state
login 我应该让 class 的 body 等于 auth
>
2 - 访问 state
register 此时它将具有相同的 auth
类
3 - 访问 state
profile 正文将具有 default 类或 none
你是如何做到这一点的?
你可以有一个主 AppController 来控制这个:
...<body class="{{ appController.bodyClasses }}">
AppController 内部:
var vm = this;vm.bodyClasses = '默认';//这将在应用程序中的每个状态更改时调用$scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){如果(angular.isDefined(toState.data.bodyClasses)){vm.bodyClasses = toState.data.bodyClasses;返回;}vm.bodyClasses = '默认';});
在你的路线定义中:
.state('注册', {网址:/注册",模板:'注册',数据: {bodyClasses: 'auth'}});
请参阅 UI 路由器文档 有关此数据属性策略的更多信息.
I'm trying to find an elegant way to have a custom dynamically class of the body tag that I can set easily from the ui-router configurations
and if none is set, I can use a default option or none.
Example:
routes.js
$stateProvider
.state('login', {
url: "/login",
template: 'Login'
})
.state('register', {
url: "/register",
template: 'Register'
}).
.state('profile', {
url: "/profile",
template: 'Profile'
});;
Simple markup HTML
<html>
<body class=""> <!-- Dynamically class to change -->
<div ui-view></div>
</body>
</html>
Scenario:
1 - Visiting the state
login I should have the class of the body equals to auth
2 - Visiting the state
register at this point it will have the same auth
class
3 - Visiting the state
profile the body will have the default class or none
How do you achieve that?
You can have a master AppController that controls this:
<html ng-app="app" ng-controller="AppController as appController">
...
<body class="{{ appController.bodyClasses }}">
Inside AppController:
var vm = this;
vm.bodyClasses = 'default';
// this'll be called on every state change in the app
$scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
if (angular.isDefined(toState.data.bodyClasses)) {
vm.bodyClasses = toState.data.bodyClasses;
return;
}
vm.bodyClasses = 'default';
});
Inside your route defs:
.state('register', {
url: "/register",
template: 'Register',
data: {
bodyClasses: 'auth'
}
});
See UI Router documentation for more on this data-attribute strategy.
这篇关于带有 Angular UI-Router 的动态主体类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!