jeremy jeremy - 7 months ago 28
Javascript Question

hide and show only input fields per object in ng-repeat angularJS

So i have a group of input fields of location and description that i am repeating over with a show and hide button for the 2nd group

so my html:

<div ng-repeat="location in vm.locations" class="row">
<div class="form-group col-md-12">
<label for="location">Location</label>
<input type="text" class="form-control" name="location" ng-model="location.name">

<a class="pull-right" ng-click="vm.showLocationDetail()">Add Description</a>
</div>
<br>
<div ng-show="vm.showDetail" class="form-group col-md-12">
<textarea class="form-control" type="text" name="description" rows="5" ng-model="location.description"></textarea>
</div>
</div>


controller:

// toggle location details
vm.showLocationDetail = function() {
return vm.showDetail = !vm.showDetail;
}


right now if i have more than 1 field of locations and i click add description...every field shows the description input field.

How do i make it so that it only shows the relevant description field?

Answer Source

This is because you are using single variable to show and hide all the description field. Use location's some property to show or hide that.

var MyApp = angular.module("MyApp",[]);
MyApp.controller("MyCtrl",['$scope',MyCtrl]);
function MyCtrl($scope) {
$scope.locations = [{name:'',description:'',showDetail : false},{name:'',description:'',showDetail : false}];
$scope.showLocationDetail = function(location) {
   location.showDetail = ! location.showDetail;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div ng-app="MyApp" ng-controller="MyCtrl">
<div ng-repeat="location in locations" class="row">
    <div class="form-group col-md-12">
        <label for="location">Location</label>
        <input type="text" class="form-control" name="location" ng-model="location.name">

        <a class="pull-right" ng-click="showLocationDetail(location)">Add Description</a>
    </div>
    <br>
    <div ng-show="location.showDetail" class="form-group col-md-12">
        <textarea class="form-control" type="text" name="description" rows="5" ng-model="location.description"></textarea>
    </div>
</div>
</div>