Search code examples
angularjscontrollerng-showangular-controller

Show and Hide Controller not working, AngularJS


I'm trying to get it so that the #water div will show when the water button is clicked and will not when the energy button is clicked. I am trying to use a controller I have made but so far it has not worked.

HTML

<head>


    <meta charset="utf-8">
    <title>test</title>
    <link rel="stylesheet" href="css/wisdom.css">
    <link rel="stylesheet" href="css/bootstrap.css">s
    <script src="http://code.jquery.com/jquery-1.12.2.min.js"></script>
    <script src="http://jquery-1.12.2.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> 
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script> 


</head>

<body ng-app="WebApp">

    <div id="water" ng-include src="'menu.html'"></div>
    </br>
    </br>


    <section ng-controller="StateController">
    <div class="btn-group" role="group" ng-model="show" >
            <button type="button" class="btn btn-primary" ng-clicked="StateController.setState(1)">Water</button>
            <button type="button" class="btn btn-warning" ng-clicked="StateController.setState(2)">Energy</button>

        </br>
        </br> 
    <div ng-include src="'panels.html'" ng-show="StateController.isSet(1)"> </div>
    </div>
    </section>

    <script src="app.js"></script>
</body>

JS

var app = angular.module('WebApp', []);
app.controller('StateController', function(){
    this.state = 1;

    this.setState = function(selectedState){
        this.state = selectedState;
    };

    this.isSet = function(givenState){
        return this.state === givenState;
    };
});

Solution

  • make the below changes

    HTML

     <div id="water"  ng-show="something" ng-include src="'menu.html'"></div>
    <button type="button" class="btn btn-primary" ng-click="setState(1)">Water</button>
                <button type="button" class="btn btn-warning" ng-click="setState(2)">Energy</button>
    

    controller.js

    var app = angular.module('WebApp', []);
    app.controller('StateController', function($scope){
        $scope.setState=function(a){
              if(a==1)
                {
                  $scope.something=true;
                }
              else{
                    $scope.something=false;
                   }
    }
    });
    

    if you want to show the water div iniatilly then add this before the setstate function in controller

    $scope.something=true;
    

    if u dont want then make it as false