单击按钮时在元素之间切换 AngularJS
Toggle between elements on button click AngularJS
我有两个 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 之间切换,但在这种情况下并没有发生这种情况。我怀疑 show 永远不会设置为 false。什么可能是我的错误。我是AngularJS的菜鸟。如何在单击按钮时实现两个元素之间的切换?提前致谢。
使用 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
首先,你必须写ng-if
而不是*ngIf
。前者表示 Angular,后者表示 AngularJS(您正在使用的 Angular 的前身)。
其次,您是对的,show
在您的代码中从未设置为 false。需要在controller中写一个可以切换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>
我有两个 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 之间切换,但在这种情况下并没有发生这种情况。我怀疑 show 永远不会设置为 false。什么可能是我的错误。我是AngularJS的菜鸟。如何在单击按钮时实现两个元素之间的切换?提前致谢。
使用 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
首先,你必须写ng-if
而不是*ngIf
。前者表示 Angular,后者表示 AngularJS(您正在使用的 Angular 的前身)。
其次,您是对的,show
在您的代码中从未设置为 false。需要在controller中写一个可以切换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>