Search code examples
javascriptangularjsangularjs-scope

AngularJS show in div if date is today, otherwise show in other div


The idea is that I have several items in my array, which have a title, company and date value. These are then shown in a div with ng-repeat.

What I want is for them to be shown in the first div if the date value is today's date and in a different div if the date value is not today. (Ideally, I would separate them in Today, Yesterday, Last Week, etc.)

What it currently does is show the dates in the first div and display their date as today, even though the value is not set like that in the array. And the second div is completely empty.

JS:

var app = angular.module("myApp", []);

app.controller("boardController", function($scope) {
    $scope.today= new Date();
    $scope.posts = [
       {
           "Title" : "Alfreds Futterkiste",
           "Company" : "Microsoft",
           "Date" : "2016-06-19",

        },{
            "Title" : "Berglunds snabbköp",
            "Company" : "IBM",
            "Date" : "2016-06-18",
        },{
            "Title" : "Centro comercial Moctezuma",
            "Company" : "MexaTel",
            "Date" : "2016-06-03",
        },{
            "Title" : "Ernst Handel",
            "Company" : "BlaBlaCar",
            "Date" : "2016-06-11",
        }
    ]
});

The HTML is structured like this:

<body ng-controller="boardController">
        <!--  Products Container  -->
        <div class="col-xs-12 col-md-8 col-md-offset-2">
            <!--  Product Container  -->
            <h2>Today</h2>
            <div class="list-group-item" ng-repeat="post in posts">
                <div ng-if="post.Date = today">
                    <h3>
                        {{post.Title}}
                    </h3>
                    <h5>
                        {{post.Date | date : 'EEE MMM d'}}
                    </h5>
                </div>
            </div>
            <h2>Yesterday</h2>
            <div class="list-group-item" ng-repeat="post in posts">
                <div ng-if="post.Date > today">
                    <h3>
                        {{post.Title}}
                    </h3>
                    <h5>
                        {{post.Date | date : 'EEE MMM d'}}
                    </h5>
                </div>
            </div>
        </div>
    </body>

Solution

  • Since Date is a string and today is Date object you need to cast them both to the same type in order to compare properly. I would use date filter to format today to the same string as Date:

    app.controller("boardController", function($scope, $filter) {
        $scope.today = $filter('date')(new Date(), 'yyyy-MM-dd');
        // ...
    });
    

    and then in HTML you would have (note === comparison operator)

    ng-if="post.Date === today"