-1

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.

Mohit Tanwani
  • 6,608
  • 2
  • 14
  • 32

4 Answers4

1

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

Community
  • 1
  • 1
Ravi Teja
  • 1,097
  • 8
  • 13
0

the ng-init directive fails to bind to the scope of the declared controller when declared like this.

famagusta
  • 160
  • 8
0

try to use "ng-init='thiss=true'" with ng-app div.

Rohit
  • 93
  • 1
  • 6
0

In second code you are using

tag as container which is wrong , tag can element like button and

itself which is fine but you should not put these element under

tag just remove p tag for and put div it will work fine.

Ayush Mishra
  • 223
  • 1
  • 3
  • 4