I am using AngularJs since long time but finding a strange issue.
The below code works well
var app=angular.module("list",[]);
app.controller("myctrl",function($scope){
$scope.get=function(){
$scope.thiss = false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!-- This code works well-->
<div ng-app="list" ng-controller="myctrl" ng-init="thiss=true">
<p>
<button ng-click="get()">Click</button>
{{thiss}}
<p ng-show="thiss">Show Content</p>
<p ng-show="!thiss">Hidden Content</p>
</p>
</div>
Facing issue with below code
If I am using following code to declare ng-app and ng-controller in HTML as below, It's not working. Strange issue
<!-- This code doesn't update scope for ng-show -->
<div ng-app="list">
<p ng-controller="myctrl" ng-init="thiss=true">
<button ng-click="get()">Click</button>
{{thiss}}
<p ng-show="thiss">Show Content</p>
<p ng-show="!thiss">Hidden Content</p>
</p>
</div>
Is there any important concept I am missing with AngularJS.
Any help in this would be greatly appreciated.
<p>
is a block-level element.
As per HTML specification
The p
element represents a paragraph. It cannot contain block-level elements (including P itself).
If nested, when HTML parser encounters inner p
element(<p ng-show="thiss">Show Content</p>
) it will implicitly close outer <p ng-controller="myctrl"...>
element.
So, once the parsing is done
<div ng-app="list">
<p ng-controller="myctrl" ng-init="thiss=true">
<button ng-click="get()">Click</button> {{thiss}}
</p><!-- paragraph is implicitly closed. So, "thiss" value is not available to ng-show -->
<p ng-show="thiss">Show Content</p>
<p ng-show="!thiss">Hidden Content</p>
</p>
</div>
You can find more discussion about nesting block elements here and here.