brohymn brohymn - 5 months ago 17
AngularJS Question

Angular (or JavaScript) , create a button that updates a field and refreshes list

I have the following HTML:

<tbody>
<tr ng-repeat="todo in todos">
<td>{{todo.userId}}</td>
<td>{{todo.id.name}}</td>
<td>{{todo.title}}</td>
<td>{{todo.completed?'COMPLETED':'INCOMPLETE'}}</td>

<td> <button type="button" ng-click="UpdateTodo()"
class="btn btn-info">Update</button> </td>
</tr>
</tbody>


I'd like to implement a button that changes the value of the field next to it. the {{todo.completed}} field.

So, this button has to change, the {{todo.completed}} field from completed to incomplete or viceversa, which is basically just a true/false value.

so in my controller I'm using ng-resource

'use strict';

app.controller("SkillController", function ($scope, UserTodos) {

$scope.todos = UserTodos.query();
$scope.UpdateTodo = function() {

UserTodos.update()


};
});


When I click the button I can see the thing trying to update something, but I get a 404 error message, if I pass variables inside the method I get 500 errors. How do I write a method inside the UserTodos.update(). so I will update ONLY {{todo.completed}} from true to false and viceversa using ngresoruce

this is my service

app.factory('UserTodos', function($resource) {
var data = $resource('http://jsonplaceholder.typicode.com/todos/:todo', {todo:'@todo'}, {
update: {
method: 'PUT'
}
});
return data;
});

Answer

First your service would need to return an object with the "Update" property you are trying to call like so...

app.factory('UserTodos', function($resource) {
    var update = function () {
        // Do Something
    }
    return {
        Update:update
    };
});

Secondly, if you want to modify the todo you can do so in the controller or in the service. Either way I would pass the index of the todo to the controller method along with the value like this.

<button type="button" ng-click="UpdateTodo($index, true)" 
                  class="btn btn-info">Update</button>

Finally in the controller you can do the manipulation or pass everything to the service.

$scope.UpdateTodo = function(index, value) {
    // Use the service
    UserTodos.update($scope.todos, index, value);

    // Or what I would do in a hurry
    $scope.todos[index].completed = value;

};