Reputation: 887
I was wondering how this can be done in AngularJS.
Having this list of keywords and an edit button next to it.
<tr ng-repeat="keyword in keywords">
<td>
<strong id="keyword.name">{{ keyword.name }}</strong>
</td>
<td>
<button ng-click="editKeyword(keyword.name)">Edit</button>
<button ng-click="deleteKeyword(keyword.name)">Delete</button>
</td>
</tr>
Now in my controller I have something like this.
$scope.editKeyword = function(name){
console.log(name);
//something done to change the <strong> element into a text input
};
How can I replace the "strong" element with a text input field via the controller. Can this be done in angularJS?
Thanks for the help.
Upvotes: 0
Views: 10227
Reputation: 11
charlietfl's suggestion:
Blockquote Simplest way would be do it directly in the template using
ng-if
ng-if
doesn't work ng-show
does.
Source: ng-click not working with ng-if
Upvotes: 0
Reputation: 507
As charlie mentionned, ng-if
would do the job.
There is also 'ng-switch', which was made exactly for this type of situation.
<tr ng-repeat="keyword in keywords">
<td ng-switch="mode[$index]">
<input ng-switch-when="edit" id="edit" ng-model="keyword.name">
<strong ng-switch-default id="keyword.name">{{ keyword.name }}</strong>
</td>
<td>
<button ng-click="editKeyword(keyword.name, $index)">Edit</button>
<button ng-click="deleteKeyword(keyword.name)">Delete</button>
</td>
</tr>
And the controller would look like:
$scope.editKeyword = function(name, index){
$scope.mode[index] = "edit";
console.log(name);
//something done to change the <strong> element into a text input
};
And you change $scope.mode[index] to anything else when you're done editing.
Upvotes: 9
Reputation: 171679
Simplest way would be do it directly in the template using ng-if
<td>
<strong id="keyword.name" ng-if="!editMode">{{ keyword.name }}</strong>
<span ng-if="editMode">
<input ng-model="keyword.name">
<button ng-click="save(keyword); editMode = false">Save</button>
<span>
</td>
<td>
<button ng-click="editKeyword(keyword); editMode = true">Edit</button>
<button ng-click="deleteKeyword(keyword)">Delete</button>
</td>
Upvotes: 7