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
4 Answers
Reset to default 3Below 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'));