最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angularjs add class to body in html - Stack Overflow

programmeradmin6浏览0评论

Hi I am developing web application in angularjs SPA application which has English and Arabic languages. For RTL and LTR properties I am trying to add class to body html element in app.js as below.

 $scope.changeLanguage = function (lang) {
        $scope.lang = lang == 'de_AR' ? 'de_AR' : 'de_EN';
        var myEl = angular.element(document.querySelector('#body'));
        myEl.addClass('rtl');
}

Using above code I am not able to add class. I can see below code in html(browser).

<body ng-controller="RoslpAppController" class="ng-scope">

May I know what is the correct way to add css classes using Angularjs?

Hi I am developing web application in angularjs SPA application which has English and Arabic languages. For RTL and LTR properties I am trying to add class to body html element in app.js as below.

 $scope.changeLanguage = function (lang) {
        $scope.lang = lang == 'de_AR' ? 'de_AR' : 'de_EN';
        var myEl = angular.element(document.querySelector('#body'));
        myEl.addClass('rtl');
}

Using above code I am not able to add class. I can see below code in html(browser).

<body ng-controller="RoslpAppController" class="ng-scope">

May I know what is the correct way to add css classes using Angularjs?

Share Improve this question edited Sep 21, 2017 at 4:46 Vivz 6,6302 gold badges18 silver badges34 bronze badges asked Sep 21, 2017 at 4:13 Niranjan GodboleNiranjan Godbole 2,1758 gold badges50 silver badges98 bronze badges 2
  • you can use ng-class for this – Paulo Galdo Sandoval Commented Sep 21, 2017 at 4:16
  • You can refer weblog.west-wind./posts/2015/may/23/… – Vivz Commented Sep 21, 2017 at 5:18
Add a ment  | 

4 Answers 4

Reset to default 3

Below is for ternary check in ng class

<div ng-class="(lang === 'de_AR') ? 'rtl' : 'ltr'"></div>

This is for multiple cases in ng class for one condition

<div ng-class="{'de_AR':'rtl', 'de_EN':'ltr'}[lang]"></div>

Code inside controller

$scope.changeLanguage = function (lang) {
        $scope.lang = lang == 'de_AR' ? 'de_AR' : 'de_EN';
        var myEl = angular.element(document.querySelector('#body'));
        myEl.addClass('rtl');
}

You are looking for ngClass directive . if you have a scope variable $scope.rtl that drives what part of your content is displayed, you can use ng-class to add dynamic classes:

 <body ng-controller="MainCtrl" ng-class="{'rtl'}">

DEMO

you can use ng-class

<body ng-controller="RoslpAppController" ng-class="{'class1':lang == 'de_AR', 'class2': lang == 'de_EN'} ng-scope">

Your code does not work because

angular.element(document.querySelector('#body'));

looks for an element with the id 'body' if you want to acces the body, use:

angular.element(document.querySelector('body'));
发布评论

评论列表(0)

  1. 暂无评论