Max Lynn
Max Lynn

Reputation: 1778

Angular ng-if isn't hiding if the value is true

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.

Upvotes: 1

Views: 1766

Answers (4)

Dinesh Vaitage
Dinesh Vaitage

Reputation: 3183

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>

Upvotes: 2

Reyraa
Reyraa

Reputation: 4274

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.

Upvotes: 1

Max Lynn
Max Lynn

Reputation: 1778

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.

Upvotes: 0

Vinoth Rajendran
Vinoth Rajendran

Reputation: 1211

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>

Upvotes: 0

Related Questions