Ketus
Ketus

Reputation: 123

How to modify data fetched by ngResource and then return it?

I'd like to modify (filter) an array in an angular service (data I've got by ngResource) and then pass the modified data to controller, but I'm stuck due to it's asynchronous behaviour.

Here's the code:

(function() {
'use strict';

angular.module('app').factory('Report', ['Employee', function(Employee) {

    var getReports = function(employeeId) {

        return Employee.query({}, function(employees) {
            return employees.filter(function(element) {
                return employeeId === element.managerId;
            });
        });

    };

    return {
        query: function(employee) {
            return getReports(parseInt(employee.employeeId));
        }
    };

  }]);
}());

And I invoke it in controller like this:

$scope.employees = Report.query({employeeId: $routeParams.employeeId});

I have two issues with the above code:

  1. it doesn't work :) getReports() returns whole employees array, without filtering,
  2. it doesn't seem like elegant or maintainable design. What can I improve in that regard?

Upvotes: 0

Views: 68

Answers (1)

VRPF
VRPF

Reputation: 3118

If you need different types on filters, you could pass a filter function as a parameter:

return {
    query: function(employee, filterFunction) {
        return getReports(parseInt(employee.employeeId)).filter(filterFunction);
    }
};


Report.query({employeeId: $routeParams.employeeId}, function (value) {
    // extra filtering...   
});

Upvotes: 1

Related Questions