2015-10-30 5 views
0

я хотел бы создать фильтр пользовательских AngularJS с использованием даты, но в первый мой фильтр не работает ...Фильтр по датам с AngularJS

app.filter('calculEndDate', function() { 
 
    // here I want to add "duration" to the date 
 
    // month or year according to "durationType" 
 
    return function(date) { 
 
    return date; 
 
    } 
 
});
<select ng-model="durationType"> 
 
    <option>month</option> 
 
    <option>year</option> 
 
</select> 
 
<input type="number" ng-model="duration"> 
 
<label for="startDate">startDate</label> 
 
<input type="text" ng-model="startDate"> 
 
<input type="text" ng-value="startDate | calculEndDate">

Мой главный вопрос: endDate является null, и я не знаю, как действовать, чтобы применить свой фильтр, когда startDate не пусто ..

+0

Пожалуйста, дайте мне знать, если мой ответ решил вашу проблему, приняв его или комментировать его, если есть проблема :) – IggY

ответ

2

var app = angular.module("App", []); 
 
app.filter('calculEndDate', function() { 
 
    // here I want to add "duration" to the date 
 
    // month or year according to "durationType" 
 
    return function(date, duration, duration_type) { 
 
    var date = new Date(date); 
 
    if (duration && duration_type === "month") 
 
     date.setMonth(date.getMonth() + duration); 
 
    if (duration && duration_type === "year") 
 
     date.setFullYear(date.getFullYear() + duration) 
 
    return date; 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<body ng-app="App"> 
 
<select ng-model="durationType"> 
 
    <option>month</option> 
 
    <option>year</option> 
 
</select> 
 
<input type="number" ng-model="duration"> 
 
<label for="startDate">startDate</label> 
 
<input type="text" ng-model="startDate"> 
 
<input type="text" ng-value="startDate | calculEndDate: duration:durationType"> 
 
{{startDate | calculEndDate: duration:durationType}} 
 
    </body>

+0

Спасибо, это работает. – tonymx227

1

Добавить параметры к фильтру:

app.filter('calculEndDate', function() { 
     // here I want to add "duration" to the date 
     // month or year according to "durationType" 
     return function(date,duration, durationType) { 
      //your code managing duration and durationType 
     } 
}); 


<select ng-model="durationType"> 
     <option>month</option> 
     <option>year</option> 
</select> 
<input type="number" ng-model="duration"> 
<label for="startDate">startDate</label> 
<input type="text" ng-model="startDate"> 
<input type="text" ng-value="startDate | calculEndDate : duration : durationType">