1

I am new on AngularJs and I want to see header when only checkbox value is true. I set its initial value false but header is showing in first running. My question is why header is showing in first time without any click?

var app = angular.module("myApp", []);
app.controller("myController", function($scope) {
  $scope.myVar = "false";
});
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myController">
  <form>
    <input type="checkbox" ng-model="myVar">if u want to see header click this checkbox</input>
    <h1 ng-show="myVar">show this if checkbox returned true</h1>
    </br>
    {{myVar}}
  </form>
</div>
Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
Pronto
  • 179
  • 1
  • 2
  • 11

3 Answers3

0

you are assigning a string to myVar, thus coercing it to boolean, it always comes true. Assign it to a real boolean: $scope.myVar = false

weisk
  • 2,468
  • 1
  • 18
  • 18
0

Because of you assigned value is a string . Just give only boolean value that's working fine.

<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>  
    <div ng-app="myApp" ng-controller="myController">
        <form>
            <input type="checkbox" ng-model="myVar">if u want to see header click this checkbox</input>
            <h1 ng-show="myVar">show this if checkbox returned true</h1></br>
            {{myVar}}
        </form>
    </div>
<script>
    var app=angular.module("myApp",[]);
    app.controller("myController",function($scope){
        $scope.myVar=false;
    });
</script>
</body>
</html>
VjyV
  • 344
  • 2
  • 13
0

Remove quotation marks from $scope.myVar = "false"; Here you are assigning a string value to $scope.myVar and hence when you load on your page for the first time it doesn't work as it does not get the desired boolean value.

Esha
  • 1
  • 2