1

I'm trying to understand why ng-if isn't showing the right content.

<div ng-if="user.premium">
     <p>If user.premium is true show this content</p>
</div>
<div ng-if="!user.premium">
     <p>If user.premium is false show this content</p>
</div>

This seems to be the way I would expect it to work. I've done a console.log on user.premium and it returns the following data.

premium: false; 

In this instance I would believe that the content to be shown would be the false content.

In this case I'd expect only the true content to show.

premium: true;

However on both true and false I'm getting the true content showing in my DOM.

How would I go about showing the correct content if the property is true or false.

6
  • Are you sure that 'true' and 'false' are boolean and not strings? Commented Dec 23, 2015 at 11:18
  • Thanks for your comment, they are 100% boolean Commented Dec 23, 2015 at 11:20
  • It works: jsfiddle.net/michelem09/8k580s95/1 Commented Dec 23, 2015 at 11:21
  • but console.log(user.premium) what does return? Commented Dec 23, 2015 at 11:22
  • if you console log user.premium you get premium: true or true? sorry just to clarify it :) Commented Dec 23, 2015 at 11:22

4 Answers 4

2

Try this solution..

make sure "user", it is object in your controller. like this..

$scope.user = {};
$scope.user.premium = false; //default value

If you can assigned any value to "$scope.user.premium"

$scope.user.premium = true; // Or any other value 

Definitely it will work...

<div ng-if="user.premium">
    <p>If user.premium is true show this content</p>
</div>
<div ng-if="!user.premium">
     <p>If user.premium is false show this content</p>
</div>
Sign up to request clarification or add additional context in comments.

Comments

1

There are some situations resulting this bug. I try to remark two:

  • You may need to manually $apply your changes on scope after making it false. This happens when you change a value in scope in in a wrapper which doesn't call for $apply natively.
  • You may use the variable scope but you have a variable with the same name in the $rooScope or a child scope.

Comments

0

If you are using As controller(MainController as mainCtrl). You should use like this

<div ng-if="mainCtrl.user.premium">
     <p>If user.premium is true show this content</p>
</div>
<div ng-if="!mainCtrl.user.premium">
     <p>If user.premium is false show this content</p>
</div>

Comments

0

I've been a complete plonker and forgot to add the values to my scope..

The answer is adding scope.user = user; to my controller. Yes without the dollar because our set up is odd.

For a proper set up you should use the dollar.

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.