【问题标题】:Angularjs toggle div visibilityAngularjs 切换 div 可见性
【发布时间】:2015-12-26 02:52:57
【问题描述】:

我试图在单击按钮时切换 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;
}

【问题讨论】:

    标签: javascript html css angularjs toggle


    【解决方案1】:

    你可以像这样简化它

    <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)

    【讨论】:

    • @Chandana 你指的是哪一部分?因为您使用的小提琴没有正确连接。
    • @Chandana 你没有引导那个小提琴,检查我的工作小提琴的例子。我已经为这两种方法添加了工作小提琴示例。
    【解决方案2】:

    我改变了你的指令..

    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/

    【讨论】:

    • 所选答案不起作用。这适用于任何可能发现此问题的人。
    【解决方案3】:

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

    【讨论】:

    • "message": "ReferenceError: angular is not defined",
    猜你喜欢
    • 1970-01-01
    • 2013-08-05
    • 2013-07-12
    • 2014-03-02
    • 2020-10-30
    • 1970-01-01
    • 2010-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多