Angularjs 切换 div 可见性

Angularjs toggle div visibility

我正在尝试通过单击按钮来切换 div 文本。我尝试使用范围变量并根据该变量切换类名。我错在哪里了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;
}

你可以像这样简化很多

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

Fiddle example

除非你需要特定的 ng-class 来切换,在这种情况下你可以做类似的事情

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

Fiddle example

(只要确保您使用的是较新版本的 angular)

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

html

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

控制器

function ctrl($scope) {    

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

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

另一种方法... 使用 ng-switch
您可以在多个 div 之间切换而不会 css 麻烦...

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>