Sohil Sohil - 3 months ago 10
AngularJS Question

AngularJS: Why is the ng-controller behaving odd with ng-show and ng-click and <p> tag?

Here's the code snippet of the Angular js app.



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>
<div ng-app="list" ng-init="thiss = true">
<p ng-controller="myctrl">
<button ng-click="get()">Click</button>
<p ng-show="thiss">This is it</p>
</p>
</div>





i have been learning AngularJS. I cannot understand why this simple example fails to work. I have been followng w3cschools tutorial and the syntax seem to perfect align with it. Is it something to with scoping ? or do i have to bind ng-show with model data.

I also did the following but it doesnot seem to work.

<div ng-app="list" ng-init="thiss = true">
<p ng-controller="myctrl" >
<button ng-click="thiss=false">Click</button>
<p ng-show="thiss"> This is it</p>
</p>
</div>


Why is placing the controller on the div tag works ? But fails to work when it is in the child element?

Answer

Please, don't try to make your HTML standard, follow some rule defined by HTML. Don't put nested <p> tags. AngularJS sometimes don't work for invalid DOM. I used <span> tag instead of nested <p> works fine.

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>
<div ng-app="list" ng-init="thiss = true">
  <p ng-controller="myctrl">
    <button ng-click="get()">Click</button>
    <span ng-show="thiss">This is it</span>
  </p>
</div>

For more information validate HTML. Please, check following HTML code at: https://validator.w3.org/#validate_by_input

<!doctype html>
<html>
<head>
<title>Test</title>
</head>
<body>
<p>
<p>
</p>
</p>
</body>

</html>
Comments