Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom filter between two dates AngularJS

I am trying to implement a custom filter that returns items that have a 'completed_date' between two date ranges.

However, I am finding that I need access to $scope inside my filter in order to grab the two dates 'picked' from the datepickers.

I don't think I can use an ng-change function as I have multiple other filters, and therefore need to ensure they all work together.

<select ng-model="userSelect" ng-options="user.id as user.name in usersObj"></select>

<select ng-model="departmentSelect" ng-options="department.id as department.name in deptObj"></select>

<div ng-repeat="post in postsList | dateRange | filter: {user_id: userSelect || undefined}: true | filter: {department_id: departmentSelect || undefined}: true">...</div>

The two datepickers are as follows:

<input type="date" ng-model="to_date">
<input type="date" ng-model="from_date">

And my filter in my controller;

.filter('dateRange', function() {
        return function( items ) {
            var filtered = [];
            var from_date = Date.parse($scope.from_date);
            var to_date = Date.parse($scope.to_date);
            angular.forEach(items, function(item) {
                if(item.completed_date > from_date && item.completed_date < to_date) {
                    filtered.push(item);
                }
            });
            return filtered;
        };
    });

However, I now realise I do not have access to $scope inside my filter, which leads me to think there is a better way of doing this.

Thanks in advance.

like image 894
DJC Avatar asked Jan 06 '23 10:01

DJC


1 Answers

As well as I can analyze your problem. You dont need $scope in your custom filter. Thats why its a custom filter do whatever you want. :)

You just need to pass the models with the filter as parameters, Like

.filter('dateRange', function() {
        return function( items, fromDate, toDate ) {
            var filtered = [];
            //here you will have your desired input
            console.log(fromDate, toDate);
            var from_date = Date.parse(fromDate);
            var to_date = Date.parse(toDate);
            angular.forEach(items, function(item) {
                if(item.completed_date > from_date && item.completed_date < to_date) {
                    filtered.push(item);
                }
            });
            return filtered;
        };
    });

And then use it in your HTML like this.

<div ng-repeat="post in postsList | dateRange : from_date : to_date | filter: {user_id: userSelect || undefined}: true | filter: {department_id: departmentSelect || undefined}: true">...</div>

Hope it helps.

like image 134
M. Junaid Salaat Avatar answered Jan 18 '23 23:01

M. Junaid Salaat