Javascript Angularjs 切换 div 可见性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32830190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:16:07  来源:igfitidea点击:

Angularjs toggle div visibility

javascripthtmlcssangularjstoggle

提问by Kurkula

I am trying to toggle a div text on click of a button. I tried taking a scope variable and toggeling classname based on the variable. Where am I making the mistake here

我试图在单击按钮时切换 div 文本。我尝试使用范围变量并根据变量切换类名。我在哪里做的错误这里

<button ng-click="toggle()">test </button>
    <div ng-class="{{state}}" >
        hello test
    </div>


function ctrl($scope) {    
    $scope.state = vis;
    $scope.toggle = function () {
      state = !state;
    };
}

 .vis{
      display:none;
}

回答by ajmajmajma

You can simplify this a lot like so

你可以像这样简化很多

<button ng-click="showDiv = !showDiv">test </button>
<div ng-show="showDiv" >
    hello test
</div>

Fiddle example

小提琴示例

Unless you need the specific ng-class to toggle in which case you can do something like

除非您需要特定的 ng-class 进行切换,否则您可以执行以下操作

<button ng-click="showDiv = !showDiv">test </button>
<div ng-class="{'vis' : showDiv }" >
    hello test
</div>

Fiddle example

小提琴示例

(just make sure you're using a newer version of angular for this)

(只需确保您为此使用了较新版本的 angular)

回答by Kashif Mustafa

I have changed your directive..

我已经改变了你的指令..

html

html

    <button ng-click="toggle()">test </button>
<div ng-show="state" >
    hello test
</div>

Controller

控制器

function ctrl($scope) {    

    $scope.toggle = function () {
      $scope.state = !$scope.state;
    }; }

see complete code here http://jsfiddle.net/nw5ndzrt/345/

在此处查看完整代码 http://jsfiddle.net/nw5ndzrt/345/

回答by Gi1ber7

Another approach...Use ng-switch
You can toggle through multiple divs without the css hassle...

另一种方法......使用ng-switch
你可以在没有css麻烦的情况下切换多个div......

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
 
}
<script src="https://code.angularjs.org/angular-1.0.1.js"></script>
<body ng-app="myApp">
<div ng-controller="MyCtrl">
 <button ng-click="showDiv = !showDiv">test </button>
 <div ng-switch="showDiv" >
   <div ng-switch-default>
  hello you
   </div>
   <div ng-switch-when=true>
  hello me
   </div>
 </div>
</div>
</body>