Angularjs切换div可见性

时间:2015-09-28 19:16:35

标签: javascript html css angularjs toggle

我试图在点击按钮时切换div文本。我尝试根据变量获取范围变量和toggeling classname。我在哪里犯了错误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;
}

3 个答案:

答案 0 :(得分:29)

你可以像这样简化这个

<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

(只是确保你为此使用更新版本的角色)

答案 1 :(得分:13)

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

<强> 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/

答案 2 :(得分:2)

另一种方法...... 使用 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>