javascript 如何以角度设置身体类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20100605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:42:43  来源:igfitidea点击:

How to set the body class in angular?

javascriptangularjs

提问by Erab BO

I'm trying to add to the body a class "bodyLogin" when in login page and remove it for all other pages. How should it be done in the angular way?

我试图在登录页面中向正文添加一个“bodyLogin”类,并为所有其他页面删除它。应该如何以角度方式完成?

回答by Erab BO

As Jeremy advised I used the ng-class but still had an issue with the auto set of the $scope value inLoginPage to effect the body class. The answer is very simple using the scope inheritance of Angular. The code for implementing body class change dynamically is in this plunkr.

正如 Jeremy 所建议的,我使用了 ng-class,但仍然存在自动设置 $scope 值 inLoginPage 来影响 body 类的问题。使用 Angular 的作用域继承,答案非常简单。动态实现 body 类更改的代码在这个plunkr 中

app.controller('profileController', function($scope) {
  $scope.setBodyClass('profile');
});
app.controller('loginController', function($scope) {
  $scope.setBodyClass('login');
});

//the controller can use either the bodyService or the app.value bodyClass
//app.controller('bodyController', function($scope, bodyService) {
app.controller('bodyController', function($scope, bodyClass) {
  $scope.setBodyClass = function(_bodyCLass) {
    $scope.bodyClass = _bodyCLass;
    $scope.inLoginPage = ($scope.bodyClass === 'login');
  };
});

Update: I changed the plunk to be more clear. the plunk shows now that you can use either the service or the value.

更新:我将 plunk 更改为更清晰。plunk 现在显示您可以使用服务或值。

回答by Jérémy Dutheil

You can use the ng-classdirective, that allow you to dynamically define a class according to an angularjs expression ; you just have to put this directive inside your bodytag, and then update your model to reflect page's id

您可以使用该ng-class指令,该指令允许您根据 angularjs 表达式动态定义一个类;您只需将此指令放在您的body标签中,然后更新您的模型以反映页面的 id

More information on ng-class: http://docs.angularjs.org/api/ng.directive:ngClass

更多信息ng-classhttp: //docs.angularjs.org/api/ng.directive: ngClass

EDIT : be careful with the syntax, as it written in the documentation ; easiest way for your context would be to use the array syntax ng-class="{{ [ myAttribute ] }}"

编辑:注意语法,因为它写在文档中;您的上下文的最简单方法是使用数组语法ng-class="{{ [ myAttribute ] }}"