ParanoidPenguin ParanoidPenguin - 5 months ago 9
AngularJS Question

Angular and ng-show not disabling items

I'm having a problem where ng-show isn't working as I'd like it to. Basically, when I click on a given panel, I'd like it to display the information for that tab. I'm trying to control it using ng-show but I can't seem to find what is wrong:

<!doctype html>
<html ng-app="store">
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<link rel="stylesheet" type="text/css" href="CodeSchool Angular/bootstrap-3.3.6-dist/css/bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>

<body ng-controller="StoreController as store">
<ul class="list-group">
<li class="list-group-item" ng-repeat="product in store.products">
<h3>
{{product.name}}
<em class="pull-right">{{product.price | currency }}</em>
<img ng-src="{{product.images[0].full}}" class="product-image"/>
</h3>
<section>
<ul class="nav nav-pills">
<li><a href ng-click="tab=1">Description</a></li>
<li><a href ng-click="tab=2">Specifications</a></li>
<li><a href ng-click="tab=3">Reviews</a></li>
</ul>


<div class="panel" ng-show=="tab===1">
<h4>Description</h4>
<p>{{product.description}}</p>
</div>
<div class="panel" ng-show=="tab===2">
<h4>Specifications</h4>
<blockquote>None yet</blockquote>
</div>
<div class="panel" ng-show=="tab===3">
<h4>Reviews</h4>
<blockquote>None yet</blockquote>
</div>

</section>
</li>
</ul>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>


I know I'm probably just missing something silly, but any help would be most appreciated.

Answer

The problem is you had defined tab and changing it inside ng-repeat itself. Basically ng-repeat does create new scope inside itself. For more details look at this similar answer

Change tab to product.tab

HTML

<section>
    <ul class="nav nav-pills">
        <li><a href ng-click="product.tab=1">Description</a></li>
        <li><a href ng-click="product.tab=2">Specifications</a></li>
        <li><a href ng-click="product.tab=3">Reviews</a></li>
    </ul>
    <div class="panel" ng-show=="product.tab===1">
        <h4>Description</h4>
        <p>{{product.description}}</p>
    </div>
    <div class="panel" ng-show=="product.tab===2">
        <h4>Specifications</h4>
        <blockquote>None yet</blockquote>
    </div>
    <div class="panel" ng-show=="product.tab===3">
        <h4>Reviews</h4>
        <blockquote>None yet</blockquote>
    </div>
</section>

As said by @developer033 in comment, you could make it more better by using ng-switch directive instead of having 3 ng-show directives.