0

I am trying to toggle a div on button click like as bellow.

This is working.

<div>
    <button ng-click='x = ! x'>toggle</button>
</div>  
<div  ng-include="'pages/include/search.html'" ng-show='x'></div>

This is not working.

<div ng-if="$state.current.url!='/splash'" >
    <button ng-click='x = ! x'>toggle</button>
</div>  
<div  ng-include="'pages/include/search.html'" ng-show='x'></div>

Why it is not working, when I add ng-if="$state.current.url!='/splash'" ?

1

1 Answer 1

1

Well,

Every angular directive create new scope

In the code below

<div ng-if="$state.current.url!='/splash'" >
   <button ng-click='x = ! x'>toggle</button>
  </div>  
 <div  ng-include="'pages/include/search.html'" ng-show='x'></div>

The ng-if directive create new scope.And withing this scope the value of x is updated on button click.But this new value of x is not accessible outside this ng-if div as it is local to that scope and it is primitive type. Since this x is primitive type so there is no data update as reference are differant.

You should use object model instead.

Here is the updated HTML

<div ng-if="$state.current.url!='/splash'" >
   <button ng-click='x.showHide = ! x.showHide'>toggle</button>
  </div>  
 <div ng-include="'pages/include/search.html'" ng-show='x.showHide'>This is div</div>

define x like this one in your controller.

$scope.x = {showHide:false}

EDIT-

In your first woking HTML, there is not directive on div.So, both these DIV come under same scope.So,x accessible across this two DIV with updated value.

<div>
<button ng-click='x = ! x'>toggle</button>
</div>  
<div  ng-include="'pages/include/search.html'" ng-show='x'></div>
Sign up to request clarification or add additional context in comments.

2 Comments

but if we use ng-show instead of ng-if its working. can you please explain more..
Can u please add plunker?

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.