Trying to figure out how to create a custom Angular 1.5 filter to format values of different object properties. The HTML file includes this code inside an ng-repeat:
<div>{{::object.day || object.date || 'Something else'}}</div>
Since backend sends object properties with the possibility of null values, the code logic dictates that if the 'day' property is not null, render it; if the 'date' property is not null, render it. If both are null, render 'Something else'.
This logic will be used in multiple places in the app, so creating a custom Angular filter is preferable.
Here's the filter I created:
angular.module('my-app', []).
filter('my-filter', my-filter);
function myFilter($filter){
return function(inputDay, inputDate) {
if(inputDay) {
var day = $filter('date')(new Date(inputDay), 'EEE');
return day;
}
else if(inputDate) {
var date = $filter('date')(new Date(inputDate), 'M/d/yyyy');
return date;
}
else {
return 'Something else';
}
}
}
In the HTML:
<div>{{::object.day | myFilter:{object:day} || object.date | myFilter:{object:date}}}</div>
The 'Something else' part is omitted in the HTML expression because the filter should handle the case when both 'inputDay' and 'inputDate' are null.
The issue may lie in the HTML condition, as the filter appears to only work for the first part - when 'day' property is not null. It works for items in ng-repeat where this property is not null. However, for the case when 'date' is not null, the filtering result is {}. The same goes for when both 'day' and 'date' are null, instead of 'Something else', it shows {}.
Upon debugging, it seems the object property is 'undefined'.
Object {myobject: undefined}
Where did I go wrong? Any suggestions are welcome.