0

I am using AngularJS 1.05

I'd like to have something like this:

In my controller:

$scope.location = $location.path().split('/')[2]
$scope.lang = $routeParams.lang
$scope.bodyClassName = ((if $scope.location isnt "login" then "sub" else ""))

I'd like to report these variables in an document object to get for example:

<div class="home en sub"></div>

I tried with

<div class="{{location}} {{lang}} {{bodyClassName}}"></div>

It works on the first load but not when the view get refresh.

As the documentation says, ng-class is made to evaluate expressions, but I need to print a variable.

What is the good way for that?

2 Answers 2

4

You need to watch the $location.path() to pick up route changes and update scope variables accordingly:

$scope.$watch(function() {
  return $location.path();
}, function(newPath) {
  $scope.location = $location.path().split('/')[2]
  $scope.lang = $routeParams.lang
  $scope.bodyClassName = ((if $scope.location isnt "login" then "sub" else ""))
});

and then, in your markup, as you have tried:

<div class="{{location}} {{lang}} {{bodyClassName}}"></div>

Another variation of the above is to update scope variables only on the route change success event and not in every watch.

Sign up to request clarification or add additional context in comments.

1 Comment

Watching $location.path() looks like a good idea but it makes problem with $digest as it seems like a new object is created when the location changes.
0

You could do:

<div class="location + ' ' + lang"></div>

or,

<div class="[ location, lang ].join(' ')"></div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.