Search code examples
javascriptangularjsangularjs-directiveangularjs-scopeangularjs-ng-repeat

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


'use strict';

app.controller("derpCont", function  ($scope,  derptod) {

        $scope.derp = derptod.query();
        $scope.deptod = function() {

            derptod.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('derptod', function($resource) {
        var cray = $resource('jpholder/tod', {
            update: {
                method: 'PUT'
            }
        });
    return cray;
});

Solution

  • 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 (todos, index, value) {
            // Do Something
            todos[index].completed = value;
        }
        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;
    
    };