Filtering time dynamically in Angular.js

In my database, I have a table named events:

id|  event   |  start_time |  end_time |
1 | wake up  |  10:00:00   | 10:15:00 |
2 | play     |  11:00:00   | 12:00:00 |
3 | walk     |  14:00:00   | 14:30:00 |

I am using ng-repeat to loop through this table and attempting to create a custom filter to display only events that are currently happening based on their time. Ideally, only one event should be displayed at any given moment. Below is my attempt:

This is how I fetch the events data from MySQL and prepare it as JSON for AngularJS:

<?
    mysql_connect("localhost","root","");
    mysql_select_db('organaizer');
    $sql = mysql_query('SELECT * FROM events');
    while($event = mysql_fetch_array($sql))
        {
            $rows[] = $event;
        }
    print json_encode($rows);
?>

The events are retrieved successfully without any errors. AngularJS code:

function eventsCtrl($scope, $http)
    {
        $http({method: 'POST', url: 'events.php'}).success(function(data)
            {
                $scope.events = data; // response data 
            });
        $scope.currentTime = function(event)
            {
                //Filter by current time
            }
    }

The HTML markup:

<div class='well' style='margin:10px;' ng-app ng-controller="eventsCtrl">
<div class="table-responsive">
  <table class="table table-bordered">
    <tr>
        <th>#</th>
        <th>Event</th>
        <th>Start Time</th>
        <th>End Time</th>
    </tr>
    <tr ng-repeat="event in events | filter:currentTime">
        <td>{{event.id}}</td>
        <td>{{event.event}}</td>
        <td>{{event.start_time}}</td>
        <td>{{event.end_time}}</td>
    </tr>
  </table>
</div>

I attempted to use a filter similar to the example provided on angularjs.org using the time format "HH:mm:ss" but was not successful. Any alternative ideas or solutions would be greatly appreciated.

Answer №1

I have implemented the "my-current-time" directive using $interval.

While there might be alternative solutions, this one gets the job done.

For more details, please check the comments within the code.

HTML:

<body ng-app="Ang" ng-cloak>
    <div class='well' style='margin:10px;' ng-controller="eventsCtrl">
        <input type="text" my-current-time="format">
        <div class="table-responsive">
            <table class="table table-bordered">
                <tr>
                    <th>#</th>
                    <th>Event</th>
                    <th>Start at</th>
                    <th>End at</th>
                </tr>
                <tr ng-repeat="event in events | filter:currentTime"> <!-- filtering based on time_from as 10:00:00 -->
                    <td>{{event.id}}</td>
                    <td>{{event.descr}}</td>
                    <td>{{event.time_from}}</td>
                    <td>{{event.time_to}}</td>
                </tr>
            </table>
        </div>
    </div>
</body>

Javascript

var app = angular.module('Ang', [])
        .controller('eventsCtrl', eventsCtrl)
        .directive('myCurrentTime', function($interval, dateFilter) {
            return function(scope, element, attrs) {
                var format,
                    stopTime;

                function updateTime() {
                    element.val(dateFilter(new Date(), format));
                    scope.time = element.val();
                }

                scope.$watch(attrs.myCurrentTime, function(value) {
                    format = value;
                    updateTime();
                });

                stopTime = $interval(updateTime, 1000);

                element.bind('$destroy', function() {
                    $interval.cancel(stopTime);
                });
            }
        });

function eventsCtrl($scope, $http, dateFilter)
{
    $http({method: 'GET', url: 'events.php'}).success(
        function(data)
        {
            $scope.events = data;
        }
    );
    $scope.currentTime = function(lesson)
    {
        return ($scope.time >= lesson.time_from && $scope.time <= lesson.time_to)
    };

    $scope.format = 'h:mm:ss';
    $scope.time = dateFilter(new Date(), $scope.format);

}

And the PHP:

<?php

    mysql_connect("localhost","root","");
    mysql_select_db('organaizer');
    $sql = mysql_query('SELECT * FROM events');

    while($lesson = mysql_fetch_object($sql)) 
    {
        $rows[] = $lesson;
    }
    echo json_encode($rows);

?>

I hope this explanation is helpful!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The problem of having an undefined state in Vuex arises

https://i.stack.imgur.com/52fBK.png https://i.stack.imgur.com/GcJYH.jpg There is an error occurring: TypeError: Cannot read property 'state' of undefined ...

Optimizing row display for each page with Material UI's pagination feature

I've been attempting to utilize Material UI table pagination to show 5 rows per page, but for some reason it displays all items on the page and doesn't switch between pages. I'm having trouble figuring out where I'm going wrong. To help ...

Using ng-model with ng-repeat element

There is a situation where I need to replicate the <li> item and incorporate a dynamic model for writing click events. <ul class="flights trip1-list" ig-init="trip1_fare = 0"> <li ng-repeat="data in flt_det" ng-click="addUp($event)" ng ...

Calculating the highest average in MySQL grouped by two fields

I am currently working on a task that involves analyzing data from the table x: id | rssi | Loc 160 | -83 |51 160 | -61 |51 161 | -80 |51 163 | -81 |51 161 | -88 |52 161 | -82 |53 My goal is to calculate the maximum avera ...

The value of $index remains constant for every page that utilizes dir-paginate

Currently, I am utilizing the dirPaginate directive to handle pagination within my Angular application. While it is functioning correctly overall, I have encountered an issue where each page displays 10 records but the $index values are not incrementing ...

Using ngTemplateOutletContext in conjunction with ng-template and a for loop to reference values in Angular will result in an error if the specified variable does not exist

Here is an example of an Array containing a component: <ng-container [ngTemplateOutlet]="controlArrayContainer" [ngTemplateOutletContext]="{controls:control?.componentProperty?.formArray, index: i}"> </ng-container> T ...

After adding Angularjs code to my webpage, I am encountering an issue where I am unable to use the right-click function

I've been putting together a mock website to showcase my ideas, utilizing a blend of HTML5, Bootstrap, and AngularJS. Everything was smooth sailing until I introduced some AngularJS code - suddenly, the right-click menu ceased to function in Chrome. ...

Display the JSON data in a table when the button is clicked

My goal is to display JSON data retrieved from a web service in a table format only after a button click. Although I have successfully fetched the data, I want it to be visible in a table only upon clicking the button. The current code displays table row n ...

Issue with decompressing the identical data using zlib (Z_BUF_ERROR)

Below is the Python code snippet I am working with: import zlib raw = bytes.fromhex("789C34C9410AC2301005D0BBFC752289A88BB94A53CAD8061B48D3329D2A1A7277DDB87BF02A14548E9C0DF63FD60DE49DC104AA98238BDE23EB908A467972065DFCF9FAFB4185C708EAD0053C58E38BDF769 ...

The React function is encountering a situation where the action payload is not

I encountered an error stating Cannot read property 'data' of undefined switch (action.type){ case REGISTER_USER: console.log("Action ", action);// This prints {type: "REGISTER_USER", payload: undefined} return [action.payload.data, ...

Angular2 (RC5) global variables across the application

I am seeking a solution to create a global variable that can be accessed across different Angular2 components and modules. I initially considered utilizing dependency injection in my `app.module` by setting a class with a property, but with the recent angu ...

In angularJS, setting the route provider is done by using the .config method

I have implemented AngularJS in my code. The main HTML file is called "mainhtml.html". <!DOCTYPE html> <html data-ng-app="demoapp"> <head> <script src="scripts/angular.min.js"></script> <title>Angular js</ti ...

Removing a row from a table seamlessly without the need to reload the page

I am having an issue with my page that displays a list of orders. When a user clicks on a button to delete a row from the table, it only removes the first row successfully. However, when attempting to delete the second or third row, it does not work. Can s ...

Ways to recycle a function across various controllers

One of my challenges involves managing multiple controllers for various routes: app.controller('FirstController', function ($scope) { $scope.func = function () { console.log('route 1'); } } app.controller('SecondController ...

Transform a formatted currency amount into a double value by utilizing regex

I need to convert various currency formats into a double value. For example: 1,000,000.00 => 1000000.00 2'345',00 => 2345.00 2'344'334.03 => 1000000.03 The current solution I have is functional but inefficient. I am explorin ...

The function myComponent.map does not exist

I am currently storing information that I am trying to pass to a component responsible for creating Tabs and TabPanel components (Material-UI) based on the provided data. Here is how the information is structured: let eventCard = [ { title: "T ...

Changing color in D3.js stacked areas when exceeding a certain threshold

While working on a project, I inherited an application that included a D3.js graph which needed to be completed. Despite not being familiar with the D3.js library initially, I managed to make some improvements. However, there is one issue I haven't be ...

Attempting to design a customized tooltip for an SVG element embedded within the HTML code

Recently, I've delved into Js with the goal of creating an interactive pronunciation guide using inline svg. If you're curious to see what I've done so far, check it out here. My current focus is on incorporating basic styled tooltips that ...

Learn how to locate the JSON path for a particular value by utilizing JavaScript

Can anyone assist with finding the JSON path for a specific value using Javascript? var data = { key1: { children: { key2:'value', key3:'value', key4: value }, key5: 'val ...

Silverstripe query that joins two tables based on specific values

I am trying to work with a many-to-many relationship between the Customer and Product classes. Here's an example: Customer Table | ID | Name | ----------------------- | 01 | Jack | | 02 | Joe | | 03 | Claire | Product Table | ID | ...