我有两个div,并希望通过单击按钮在它们之间切换。以下是我尝试过的代码:
<div id="one" *ngIf="show == true">
Hello One
</div>
<div id="two" *ngIf="show == false">
Hello Two
</div>
<button ng-init="show=true">Click to toggle</button>
我想在单击按钮时在两个div之间切换,但是在这种情况下却没有发生。我怀疑节目永远不会设为假。可能是我的错误。我是AngularJS的新手。如何在单击按钮时实现两个元素之间的切换?预先感谢。
答案 0 :(得分:1)
首先,您必须写*ngIf
而不是ng-if
。前一种表示法用于Angular,而另一种表示法用于AngularJS(您正在使用的Angular的前身)。
第二,您是对的,show
永远不会在代码中设置为false。您需要在控制器中编写一个函数,该函数可以切换show
的值,如下所示:
constructor($scope) {
$scope.show = true;
$scope.toggle = function(){
$scope.show =!$scope.show;
}
}
然后,html可以如下:
<div id="one" ng-if="show">
Hello One
</div>
<div id="two" ng-if="!show">
Hello Two
</div>
<button ng-click="toggle()">Click to toggle</button>
答案 1 :(得分:0)
使用ng-show和ng-hide实现。使用了以下内容:
<div id="one" ng-show="show>
Hello One
</div>
<div id="two" ng-hide="show">
Hello Two
</div>
<button ng-click="toggle()">Click to toggle</button>
在控制器中,添加以下内容:
$scope.show = true;
$scope.toggle = function(){
$scope.show =!$scope.show;
}
参考:How to toggle between elements in angularJS
我已经实现了我的目标,但是肯定想知道我们如何通过ng-If做到这一点