0

I'd like to create a custom AngularJS filter using dates but in first my filter doesn't work...

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">

My main issue : endDate is null and I don't know how to proceed to apply my filter when startDate is not empty..

1
  • Please let me know if my answer solved your problem by accepting it or commenting it if there is a problem :) Commented Oct 30, 2015 at 11:51

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

Comments

1

Add parameters to your filter :

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">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.