1

I have two code examples that work good, but I don't understand the difference. So, the first is:

AngularJS:

$scope.state = {presentation: true};

HTML:

<div ng-class="{{state.presentation}} ? 'on' : 'off'"></div>

And the second one:

AngularJS:

$scope.presentation = true;

HTML:

<div ng-class="presentation ? 'on' : 'off'"></div>

Why can't I use something like this in the 2-nd example:

<div ng-class="{{presentation}} ? 'on' : 'off'"></div>

When I use {{ }} with $scope.presentation = true; it doesn't work in ng-class, but I can use {{presentation}} like the text, I mean <div>{{presentation}}</div> and it works good. Why?

But with $scope.state = {presentation: true}; I can use {{presentation}} even in ng-class and it works good.

What the difference?

6
  • Probalby it's caused by writing/reading to different scope. Can you put your code in a plunker? Commented Jun 29, 2015 at 8:21
  • div>{{presentation}}</div> is this working in your 2nd example. Commented Jun 29, 2015 at 8:26
  • I have tried what you expect.Its working fine. Here is the plunker. plnkr.co/edit/b2JzP55QuhV3dDCLhof0?p=preview Commented Jun 29, 2015 at 8:34
  • Also you there is no need of interpolation you can use it as plain JavaScript object or using primitive type. plnkr.co/edit/b2JzP55QuhV3dDCLhof0?p=preview Commented Jun 29, 2015 at 8:43
  • off class doesn't work because bothe $scope.presentation and $scope.state = {presentation: true}; are set to true.If you set anyone of this to false it show red that is 'off' class is applied. Commented Jun 29, 2015 at 8:50

1 Answer 1

1

You should'nt use an expression inside a ng-attribute like that. And it will fail (without or without the state object) :

Error: [$parse:syntax] Syntax Error: Token '?' not a primary expression at column 2 of the expression [ ? 'on' : 'off'] starting at [? 'on' : 'off'].

That's normal because angularJs executes it as an angularJS expression, so when you're typing :

<div ng-class="presentation ? 'on' : 'off'"></div>

Internally angularJS executes it as an expression and it can be written also like that :

<div class="{{presentation ? 'on' : 'off'}}"></div>
Sign up to request clarification or add additional context in comments.

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.