punkouter
punkouter

Reputation: 5366

Where does the error event go in Angular when using a factory?

I have the code below working but now I need to create a handler for when an error occurs but not sure how I insert that.. Do I put it in the factory on in the main method?

MsaApp.factory('Msa', function ($resource) {
return $resource('/api/Place/:id', { id: '@id' }, { update: { method: 'PUT' } });

});

 $scope.delete = function () {
    debugger;
    var id = this.msa.PlaceId;
    Msa.delete({ id: id }, function () {
        $('#todo_' + id).fadeOut();
    });
}

edit 1:

 $scope.delete = function () {
    debugger;

    // var id = this.msa.PlaceId;

    var config = {
        method: 'PUT',
        url: 'api/Place/:id',
        data: { 'some': 'data' }
    }

    $http(config)
    .success(function (data, status, headers, config) {
        console.log(data);
    })
    .error(function (data, status, headers, config) {
        console.log(data);
    });


    //Msa.delete({ id: id }, function () {
    //    $('#todo_' + id).fadeOut();
    //});
}

Upvotes: 0

Views: 428

Answers (1)

JoakimB
JoakimB

Reputation: 1206

First of all I would sugest moving all DOM manipulation to a directive and let the controller do what its supposed to do.

And to answer your question ( hope I understood you correctly ):

MsaApp.factory('Msa',['$http', function(http) {
    return {

        delete: function(someData) {

            var config = {
                method: 'PUT',
                url: '/api/Place/:id',
                data : someData
            };

            http(config)
            .success(function(data, status, headers, config) {

                console.log(data);

            })
            .error(function(data, status, headers, config) {
                    console.log(data);
            });



        }}

    };
}])

MsaApp.controller('ControllerName', ['$scope', 'Msa', function(scope, Msa) {

    $scope.delete = function({ id: id }) { 
        debugger; 
        Msa.delete({ id: id }); 
        $('#todo_' + id).fadeOut(); 
    };

}])

If your factory cant access the controller scope and you wish to return, for example messages back to the controller you need to use a promise which is explained here: http://markdalgleish.com/2013/06/using-promises-in-angularjs-views/

Upvotes: 1

Related Questions