Matheus Souza
Matheus Souza

Reputation: 334

Angular.js add class to element when in some page

I'm trying to add the class post to my div #wrap when i'm on the page /post. That's what I have:

$routeProvider

when('/post', {
    templateUrl : 'views/post.php',
    controller  : 'postCtrl'
})

Controller

carolvaladares.controller('postCtrl', function($scope) {
    $scope.post = true;
});

HTML

<div id="wrap" ng-class="{true: 'post'}[post]">

When on /post, $scope.post is true. If the $scope.post is true, add the class post to #wrap

The thing is that when I go to /post, It does not read the $scope.post unless I use ng-controller="postCtrl" manually.

Thanks in advance.

-- EDITED --

The $scope.post returns true when I use {{post}} on /post. Still I can't work with ng-class.

-- EDITED --

The problem still happening because the #wrap is out of my ng-view. So I guess what I'm trying to do, the way I'm trying to do won't be possible.

Upvotes: 0

Views: 135

Answers (5)

Emil Nik
Emil Nik

Reputation: 29

I would suggest you try something like this:

when('/post', {
    templateUrl : 'views/post.php',
    controller  : 'postCtrl',
    activetab: 'post'
})

and add:

<div id="wrap" ng-class="{post: $route.current.activetab == 'post'}"">

Upvotes: 0

Thalaivar
Thalaivar

Reputation: 23632

<div id="wrap" ng-class="{true: 'post'}[post]">

The statement you have given for ng-class should work, could you change your post variable to something else to check if its working like below:

<div id="wrap" ng-class="{true: 'post'}[someValue]">

Apart from this, there is other solutions below which you can try:

Sol1:

<div id="wrap" ng-class="{'post': post}">

Sol2

<div id="wrap" ng-class="post ? 'post' : 'somethingelse' }">

Upvotes: 0

iamalismith
iamalismith

Reputation: 1571

ng-class works like this:

ng-class="{'classNameToApply': angularExpression}"

The 'classNameToApply' will be applied when the angularExpression evaluates to something truthy.

So in your case, to apply the class of 'post', you would do <div id="wrap" ng-class="{'post': post}">

Upvotes: 0

Knelis
Knelis

Reputation: 7129

I think the problem is your HTML:

<div id="wrap" ng-class="{ className: post === true }">

should work.

Upvotes: 1

Emil Nik
Emil Nik

Reputation: 29

Try

<div id="wrap" ng-class="{'post': post}">

Also don't forget to add the ng-controller

Upvotes: 0

Related Questions