我想使用日期创建自定义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 :(得分: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>
答案 1 :(得分: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">