1

Following are the code snippets in which I am toggling the hideQA value, the value is changing properly in both condition but not hiding the divs properly if I am doing -

`<button ng-click="hideQA = !hideQA">Reset</button>`

But it is working correctly if I am changing the value from a method, like -

`<button ng-click="resetForm()">Reset</button>`

Can anyone explain the reason behind this ?

Working Plnkr - http://plnkr.co/edit/rIAAcibX2Ts1VaMWKQtc?p=preview

1
  • I think it has to do with your comparison. I created a similar toggle earlier: jsfiddle.net/oa4b75zj Commented Apr 18, 2016 at 13:57

3 Answers 3

1

ng-if has its own $scopeand when the element is removed, the $scope removes too. So you have to reference to parent scope using $parent

<button ng-click="$parent.hideQA = !hideQA">Reset</button>

Another option is to use ng-show

<div class="message" ng-show="hideQA !== false">
    This is div two !!!
    <button ng-click="hideQA = !hideQA">Reset</button>
</div>
Sign up to request clarification or add additional context in comments.

1 Comment

it's better to use dot notation isntead of $parent.
1

This is because of the limit of inhertance between scope.

In order to have no problem with that you must use dot notation.

See the plunkr : http://plnkr.co/edit/ES9qTl7nsmGGOJnE0H8u?p=preview

See article for more explanation about dot notation

Here is what look like your code with dot notation :

<button ng-click="a.hideQA = !a.hideQA">Reset</button>
$scope.a = {hideQA:false};
$scope.a.hideQA = true;

Comments

1

Answer given above already solve this issue. Here is my working plunkr link: http://plnkr.co/edit/ZdL441bBmQToGZn4gfQt?p=preview. And I'll say something else:

When you use ng-if it will creates its own scope, from angularjs official docs :

The scope created within ngIf inherits from its parent scope using prototypal inheritance.

In a short, when refers the value from it's parent scope, only value is copied for primary type (like string, integer , boolean and etc.) but not value's reference (or pointer). Which means it is one-way reference not the two-way. So in order to use as two-way the best practice is to always use javascript object {attr: value}. And that is why . is recommended.

Here is a very good article which worth 20 mins readying about the scopes https://github.com/angular/angular.js/wiki/Understanding-Scopes

Hope this can help you :)

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.