简体   繁体   English

Angularjs 切换 div 可见性

[英]Angularjs toggle div visibility

I am trying to toggle a div text on click of a button.我试图在单击按钮时切换 div 文本。 I tried taking a scope variable and toggeling classname based on the variable.我尝试使用范围变量并根据变量切换类名。 Where am I making the mistake here我在哪里做的错误这里

<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;
}

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)

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/

Another approach... Use ng-switch另一种方法......使用ng-switch
You can toggle through multiple divs without the css hassle...您可以在没有 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM