Paul Paul - 5 months ago 22
Javascript Question

How to change text element into input field on click using AngularJS?

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.

Answer

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>
Comments