[英]ng-click not working with ng-if angularjs
I am trying to toggle a div
on button click like as bellow. 我试图像下面这样在按钮单击上切换div
。
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'"
? 当我添加ng-if="$state.current.url!='/splash'"
时,为什么它不起作用?
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. ng-if指令创建新的作用域,并在单击此按钮时更新x的值,但是在此ng-if div之外无法访问x的新值,因为它在该作用域内是本地类型,并且是原始类型。 Since this x is primitive type so there is no data update as reference are differant. 由于此x是原始类型,因此没有数据更新,因为引用是不同的。
You should use object model instead. 您应该改为使用对象模型。
Here is the updated HTML 这是更新的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. 在控制器中像这样定义x 。
$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. 在您的第一个唤醒HTML中,div上没有指令,因此,这两个DIV都属于同一范围。因此, x可以在这两个DIV中以更新的值访问。
<div>
<button ng-click='x = ! x'>toggle</button>
</div>
<div ng-include="'pages/include/search.html'" ng-show='x'></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.