Aniruddha Bhondwe Aniruddha Bhondwe - 2 months ago 7
HTML Question

AngularJS change attribute values

I have rows in table which generate buttons dynamically

<tr ng-repeat="task in task">
<td>{{task.Name}}</td>
<td>{{task.Comments}}</td>
<td>{{task.Project}}</td>
<td>{{task.Duration}}</td>
<td>
<button class={{editable}} ng-click="editTask(task.id)"></button>
<button class="glyphicon glyphicon-trash"></button>
</td>
</tr>


In my Angular code I have

$scope.editTask = function(id){
if($scope.editable == "glyphicon glyphicon-edit"){
$scope.editable="glyphicon glyphicon-floppy-save";
}
else{
$scope.editable="glyphicon glyphicon-edit"
}
}


So basically I want to change the edit glyphicon to save glyphicon and the save glyphicon back to edit glyphicon. But since I have assigned class to the button it changes the glyphicons of all buttons in the table. How can I change the icon of only the button of which is clicked?

Answer

Approach 1

You can update your HTML to

<td>
    <button class="glyphicon" ng-class="task.editable" ng-click="editTask(task)"></button>
    <button class="glyphicon glyphicon-trash"></button>
</td>

Passing the task instead of the id directly allows you to update it's editable state directly on the task. Your controller should update the editable property

$scope.editTask = function(task){
    if(task.editable == "glyphicon-edit") {
       task.editable="glyphicon-floppy-save";
    }
    else{
       task.editable="glyphicon-edit"
    }
}

Note: I've passed the glyphicon class directly to the button since it won't change.

Approach 2

You could also approach it another way and keep the condition in the HTML

<button class="glyphicon" ng-class="task.editable ? 'glyphicon-edit': 'glyphicon-floppy-save'" ng-click="editTask(task)"></button>

And your controller could just update the editable property

$scope.editTask = function(task){
    task.editable = !task.editable;
}