Akhilesh Kumar
Akhilesh Kumar

Reputation: 919

Dynamic show hide code for dynamic content angular js

Run below code as it is, Code is working fine but i want the same functionality without polluting angularjs code.

<html>
    <head>
        <title></title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    </head>
    <body ng-app="newapp" ng-controller="newctrl">
        <div ng-repeat="x in names">
            <div  data-ng-click="toggleCompanyArr(['nav_' + x.id])"><a href="">This is id : {{x.id}}</a></div>
            <div id="nav_{{x.id}}" style="display:none">{{x.firstname}} {{x.lastname}}</div><br><Br><Br>
        </div>
    </body>

<script>
var app = angular.module('newapp',[]);
app.controller('newctrl', function($scope){
    $scope.names=[
        {"id":"1","firstname":"Akhilesh","lastname":"Kumar"},
        {"id":"2","firstname":"Aman","lastname":"Kumar"},
        {"id":"3","firstname":"Mithilesh","lastname":"Kumar"}
    ];  
    $scope.toggleCompanyArr = function(val){
        $("#"+val).toggle();    
    };
});
</script>
</html>

Upvotes: 1

Views: 2223

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136184

You don't need to use jQuery to show/hide div, you could simply use ng-show here.

For achieving this you need to add show flag on each element of the names collection (you don't necessary to add new show property to your collection, if you don't add show: false prop in your each names element, angular will take care of this), and toggle show flag on click of the element. Thereafter use x.show flag inside ng-show directive to show & hide div.

Basically on initial load x.show value either undefined or false so anyhow it is going to hide the all element content on load. When you click on element ng-click directive will flag to x.show = true and that element will get shown.

The other advantage behind this approach is, you could have state of your each element in its object.

Suppose you have akhilesh option selected then it will have {"id":"1","firstname":"Akhilesh","lastname":"Kumar", show: true}, & other will have show: false if those element are not clicked.

Markup

<div  data-ng-click="x.show = !x.show">
    <a href="">This is id : {{x.id}}</a>
</div>
<div ng-show="x.show">
    {{x.firstname}} {{x.lastname}}
</div>

Reference link

Upvotes: 3

Related Questions