AngularJS - hide/show div if date is within last 6 months

十年热恋 提交于 2020-12-08 02:20:52

问题


I have an ng-repeat that displays a list of dates, and information about purchases on that dates.

HTML:

<div ng-repeat="data in MyData">
    <p>
        {{ data.purchasedOn.substring(6, data.purchasedOn.length - 2) | date:'dd/MM/yyyy' }}
    </p>
    <br>
    <p>
        {{ data.purchaseDescription }}
    </p>
</div>

Which displays:

01/02/2013
"Lorem ipsum dolor sit amet, consectetur adipisicing elit"

10/04/2014
"Lorem ipsum dolor sit amet, consectetur adipisicing elit"

02/08/2014
"Lorem ipsum dolor sit amet, consectetur adipisicing elit"

13/06/2014
"Lorem ipsum dolor sit amet, consectetur adipisicing elit"

19/02/2013
"Lorem ipsum dolor sit amet, consectetur adipisicing elit"

How can i only show the {{ data.purchaseDescription }} when purchasedOn is within the last 6 months from the current month?


回答1:


Assuming that you want to show purchasedOn but not the description, you could use a function like this one described here to determine a date 6 months prior.

function addMonths(date, months) {
  date.setMonth(date.getMonth() + months);
  return date;
}

Then define a function to get a boolean show/hide value:

function shouldHide(purchasedOn){
    var purchaseDate = Date.parse(purchasedOn);
    var sixMonthsAgo = addMonths(new Date(), -6); 
    var hide = purchaseDate < sixMonthsAgo ? true : false;
    return hide;
}

Now you can just use your function in an ng-hide in your <p> element

<p ng-hide={{shouldHide(data.purchasedOn)}}>
    {{ data.purchaseDescription }}
</p>

EDIT If you do just want to hide the entire element, you could make a filter function like this:

$scope.filterOldDates = function(date)
{
    if(shouldHide(date)){
        return false; 
    }
    return true; 
};

You would use it like this:

<div ng-repeat="data in MyData | filterOldDates">


来源:https://stackoverflow.com/questions/25198680/angularjs-hide-show-div-if-date-is-within-last-6-months

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!