Reputation: 2265
I use a ngRepeat directive to show data of persons (now I am showing only the name of the persons).
The name of the person is shown using a span tag. Also there is a button that hide the span and show an input field containg the name of the person so it can be editable.
When I press a button I need the affected span to be "converted" to input, but it's not working and all the spans are converted to inputs.
<div ng-repeat="a_person in persons.data track by $index">
<md-button aria-label="Show inputs">
<md-icon ng-click="showInput(a_person)">edit</md-icon>
</md-button>
<span ng-if="!a_person.editMode">{{a_person.name}}</span>
<input ng-if= "a_person.editMode" type="text" value="{{a_person.name}}">
</div>
I am using a table and a form but I don't show them here so it can be easy to explain.
Upvotes: 1
Views: 1065
Reputation: 27212
Try this it will work as per your expectations :
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function($scope) {
$scope.persons = {
"data": [
{
id:1,
name:"name1"
},
{
id:2,
name:"name2"
},
{
id:3,
name:"name3"
}
]
};
$scope.showInput = function(personid) {
$scope.editperid = personid;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<div ng-repeat="person in persons.data">
<a ng-click="showInput(person.id)">edit</a>
<span ng-hide="editperid == person.id">{{person.name}}</span>
<input ng-show="editperid == person.id" type="text" value="{{person.name}}">
</div>
</div>
Upvotes: 1
Reputation: 48968
<div ng-repeat="a_person in persons.data track by $index">
<md-button aria-label="Show inputs">
<!-- REPLACE
<md-icon ng-click="showInput(a_person)">edit</md-icon>
-->
<!-- WITH this -->
<md-icon ng-click="a_person.editMode = true">edit</md-icon>
</md-button>
<span ng-hide="a_person.editMode">{{a_person.name}}</span>
<!--
<input ng-if="a_person.editMode" type="text" value="{{a_person.name}}">
-->
<!-- USE ng-model directive -->
<input ng-show="a_person.editMode" type="text" ng-model="a_person.name">
</div>
I recommend using ng-show
/ng-hide
because the ng-if
directive creates a child scope which will fight with the ng-model
directive which expects no scope on that element. Also ng-if
has much more overhead because it compiles/destroys DOM while the other changes only CSS style.
Upvotes: 1
Reputation: 1313
you need to keep an array of Boolean to keep track of showing an input field or span for each item in your ng-repeat
.
$scope.showEdit = new Array(n)
$scope.showInput(index) {
$scope.showEdit[index] = !$scope.showEdit[index];
}
and finally
<span ng-if="!showEdit[$index]">{{a_person.name}}</span>
<input ng-if= "!showEdit[$index]" type="text" value="{{a_person.name}}">
Hope you get the idea.
Upvotes: 1