jgravois
jgravois

Reputation: 2579

AngularJS: Returning "Subsets" of Data from a Factory

I have this factory:

(function(){

    var requestsFactory = function(){

        var requests = [
          {id: 1, title: 'First Request', status: 'In Progress'},
          {id: 2, title: 'Second Request', status: 'Closed'},
          {id: 3, title: 'Third Request', status: 'Waiting'},
          {id: 4, title: 'Fourth Request', status: 'Closed'},
          {id: 5, title: 'Fifth Request', status, 'In Progress'}
        ];

        var factory = {};

        factory.getAllRequests = function(){ return requests; };
        /* THIS IS NEW */
        factory.getOpenRequests = function(){
          var open_requests = filter(requests.status, function(status){
            return status !== 'Closed';
          });
          return open_requests;
        };
        /* END NEW */

       return factory;
}; // end requestsFactory

        return factory;
    };

    angular.module('appITI').factory('requestsFactory', requestsFactory);
}());

And this Controller:

(function(){

    var UsersController = function($scope, usersFactory, requestsFactory){
        $scope.current_user = [];
        $scope.requests = [];
        $scope.open_requests = []; // NEW

        $scope.prefs = 'false';

        function init(){
            $scope.current_user = usersFactory.getCurrentUser();
            $scope.requests = requestsFactory.getAllRequests();
             $scope.open_requests = requestsFactory.getOpenRequests(); //NEW
        }

        init();

    }; // end UsersController

    UsersController.$inject = ['$scope', 'usersFactory', 'requestsFactory'];

    angular.module('appITI').controller('UsersController', UsersController);

}());

I need to add a method to the factory so that I can call something like this in the controller:

$scope.open_requests = requestsFactory.requestsByStatus('In Progress');

I have been so absorbed with learning AngularJs this weekend I can't seem to figure out what I bet is simple JavaScript.

NEW I have this in the template and now the page is white and broken.

<tr class="landing_data_row" data-ng-repeat="request in open_requests | filter:techFilter | orderBy:sortBy:reverse">

Upvotes: 0

Views: 182

Answers (1)

aludvigsen
aludvigsen

Reputation: 5981

Add a new function to your factory, and use the filter function.

factory.getOpenRequests = function(){
  return requests.filter(function(el){
    return el.status !== 'Closed';
  });
};

update Here is a working Plunker to your updated question.

Upvotes: 1

Related Questions