Angularjs - > ng-click和ng-show显示div

jmh*_*let 25 javascript angularjs

我只想在用户按下按钮时显示一个div,看起来很容易,但是花了很多时间后我真的很疯狂.我的代码是

我的小提琴:http://jsfiddle.net/jmhostalet/4WK7R/1/

<div ng-app>
    <div ng-controller="MyCtrl">
        <div><button id="mybutton" ng-click="showAlert()">Click me</button></div>
        <div>Value: {{myvalue}}</div>
        <div><div ng-show="myvalue" class="hideByDefault">Here I am</div></div>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

和我的控制器

function MyCtrl($scope) {

  $scope.myvalue = false;

  $scope.showAlert = function(){
    $scope.myvalue = true;  
  };
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

Ser*_*y K 12

只是摆脱display: none;你的CSS.AngularJS控制显示/隐藏该div.

如果你想默认隐藏它,scope.myvalue最初只需将值设置为false - 你已经在做了.


小智 11

<html>
<head>
    <title></title>
</head>
<body>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', [])
        app.controller('MyController', function ($scope) {
            //This will hide the DIV by default.
            $scope.IsVisible = false;
            $scope.ShowHide = function () {
                //If DIV is visible it will be hidden and vice versa.
                $scope.IsVisible = $scope.IsVisible ? false : true;
            }
        });
    </script>
    <div ng-app="MyApp" ng-controller="MyController">
        <input type="button" value="Show Hide DIV" ng-click="ShowHide()" />
        <br />
        <br />
        <div ng-show = "IsVisible">My DIV</div>
    </div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

示例: - http://jsfiddle.net/mafais/4WK7R/380/


小智 5

很简单,只要这样做:

<button ng-click="hideShow=(hideShow ? false : true)">Toggle</button>

<div ng-if="hideShow">hide and show content ...</div>
Run Code Online (Sandbox Code Playgroud)