SARAN SARAN - 28 days ago 8
AngularJS Question

ng-show and ng-hide with ng-clikc function in ng-repeat loop

I'm new to angular JS. I didn't know how to use ng-show and ng-hide with ng-click function in ng-repeat loop. Here is my code:

<div ng-repeat="listname in get_checklist track by $index">
<span ng-click="CKItemShowHide()"> Add Item </span>
<div ng-show ="CKItemIsVisible" ng-cloak class="labelBoardpopup memberBoardpopup" layout="row" layout-wrap>
<h3>Create Item</h3>
<div class="createBoardpopupform" layout="row">
<form flex>
<md-input-container class="md-block" flex-gt-sm>
<label>Item name</label>
<input ng-model="CKItem" ng-required="true">
</md-input-container>
<md-button class="md-raised md-primary">Add</md-button>
</form>
</div>
</div>
</div>


In controller i have code like this:

$scope.CKItemIsVisible = false;
$scope.CKItemShowHide = function () {
$scope.CKItemIsVisible = $scope.CKItemIsVisible ? false : true;
};


In this code when i click add item it will show and hide all div content at the same time. But i want to show individual content show and hide. If anyone can please help.

Answer

Instead of calling a method on ng-click, you can directly take a scope variable show in my example, and change it to true or false using !show

Since ng-repeat creates a new scope on every iteration, the show scope variable is always local to the current iteration.

Please check this code,

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.get_checklist = [
        {
           test: "test"
        },
        {
            test: "test"
        },
        {
            test: "test"
        }
        ];
        
        
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="MyCtrl" ng-app="myApp">
   <div ng-repeat="listname in get_checklist">
  <span ng-click="show = !show"> Add Item </span>
    <div ng-show ="show" ng-cloak class="labelBoardpopup memberBoardpopup" layout="row" layout-wrap>
        <h3>Create Item</h3>
        <div class="createBoardpopupform" layout="row">
        <form flex>
            <md-input-container class="md-block" flex-gt-sm>
                <label>Item name</label>
                <input ng-model="CKItem" ng-required="true">
            </md-input-container>
            <md-button class="md-raised md-primary">Add</md-button>
        </form>
        </div>
    </div>
</div>

Please run this snippet

Here is the fiddle

Comments