Creating a personalized Angular filter to format various object properties in version 1.5

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.

Answer №1

Feel free to give this solution a shot.

Check out the layout:

<div id="body">
  <div ng-controller="FrameController as vm">
    <div>{{vm.firstObject.day && (vm.firstObject.day|myFilter:'day') || vm.firstObject.date && (vm.firstObject.date|myFilter:'date')}}</div>
    <div>{{vm.secondObject.day && (vm.secondObject.day|myFilter:'day') || vm.secondObject.date && (vm.secondObject.date|myFilter:'date')}}</div>
  </div>
</div>

Here is the corresponding JavaScript:

angular.module('app', []).filter('myFilter', function ($filter){

return function(inputDate, formatType) {
if(formatType === 'day') {
     var day = $filter('date')(new Date(inputDate), 'EEE');
     return day;
   }
   else if(formatType === 'date') {
    var date = $filter('date')(new Date(inputDate), 'M/d/yyyy');
    return date;
   }

   return 'Something different';
}
})
.controller('FrameController', ['$injector', function($injector) {
  var vm = this;
  vm.message = 'Greetings';
  vm.firstObject = {
     day: new Date()
  };
  vm.secondObject = {
     date: new Date()
  };
}]);

setTimeout(function() {
  angular.bootstrap(document.getElementById('body'), ['app']);
});

Try it out on the demo at:

http://jsfiddle.net/2mbs3o4s/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Once the GeoJson data is loaded with map.data.loadGeoJson, the circle events are obscured by the polygons from the

When I use map.data.loadGeoJson() to load a Geo Json file, the markers and circles on my map are being covered by polygons and their events cannot be clicked. Below are some sample codes for reference. How can this issue be resolved? Is there another way ...

The JavaScript function for clearing an asp.net textbox is not functioning properly

I am working on an ASP.net project and have encountered an issue with two textboxes. When one textbox is clicked on, I want the other one to clear. Below is the code I have for the textboxes: <asp:TextBox runat="server" ID="box1" onfocus="clearBox2()" ...

Saving props in React-select

I'm currently utilizing react-select to enable multiple selection on my UI. However, I need to extract the props from react-select since I will be sending the selected values to the backend. My query is how can I store the state values in an array for ...

The error "Cannot read property 'then' of undefined" is commonly encountered in Angular.js

I am attempting to display a details page for each of my captures using my service. However, when I try to load the page with an ID in my service (for example: /capture/5740c1eae324ae1f19b7fc30), I receive undefined using this code: app.factory('cap ...

No data is being recorded in the Firestore database

This component in nextjs is designed to write data to a firestore database after the user clicks a button. Unfortunately, Firebase seems to be having trouble writing the data, even though the alert message following the supposed data dump is successful. I ...

Importing multiple exports dynamically in Next.js

My current setup involves using a third-party package that I load dynamically in Next.js: const am5 = dynamic(() => import("@amcharts/amcharts5"), {ssr: false}) The imported amcharts5 consists of various exports and imports, such as: export { ...

In React, the error message "Joke.map is not a function" indicates that

export default App I am encountering an error in this code which says joke.map is not a function. Can someone please assist me in finding a solution? I have verified the api endpoints and also checked the function. import { useEffect, useState } from &ap ...

"How can I perform a expressjs database query based on a specific user's

app.get('/user/:id', function(req, res){ fetchData(req.params.id, res); }); function fetchData(id, res) { connection.query('SELECT * FROM data WHERE name = ?' , function(err, rows){ res.render('users', {users ...

Tips for creating a versatile generic function in javascript that covers all arguments sizes

When working with node.js, a tcp server typically has several methods for listening: server.listen(port, [host], [backlog], [listeningListener]) server.listen(path, [listeningListener]) server.listen(handle, [listeningListener]) In the context of creatin ...

What is the best way to ensure the height and width of a Next.js image matches the dimensions of the original image?

Currently, I am working on setting up an image gallery with a layout similar to Masonry. This layout involves multiple columns, all with the same width, adjusting based on the viewport width. The height of each item in the gallery is flexible, depending on ...

How can I make SocketIO work with Nodejs and PHP?

I have recently developed a chat application that is designed to display received messages in real-time, without the need for manual refreshing. Currently, I am utilizing xampp and running it on port 80 for this project. Below is the code snippet include ...

How can I dynamically assign ngModel in AngularJS?

I've created a directive with an isolate scope that maps a list of objects to inputs for modifying a specific property. However, I now aim to make this component more universal by allowing it to bind to deeply nested properties within each object. Fo ...

When the value of a react state is used as the true value in a ternary operator in Types

Attempting to implement sorting on a table is resulting in the following error: (property) direction?: "asc" | "desc" No overload matches this call. Overload 1 of 3, '(props: { href: string; } & { active?: boolean; direction? ...

Is it possible to change individual pixels within a canvas without the need to duplicate the entire buffer?

Is it possible to directly alter individual pixels within a canvas, rather than retrieving the entire buffer using ctx.getImageData and then pasting it back with ctx.putImageData? This is crucial in order to avoid the costly process of copying data every ...

Customer is unable to locate the "InitializeAuthenticationService" function

After launching my application, the browser console keeps showing me three errors that all say Could not find 'AuthenticationService.init' ('AuthenticationService' was undefined). and Microsoft.JSInterop.JSException: Could not find &apo ...

Retrieve information from individual XML nodes in a parsed string

When making an Ajax call to retrieve XML data from a different domain using a PHP proxy to bypass cross-origin restrictions, I am unable to extract the values from the XML nodes and display them in my HTML tags. Despite no errors showing up in the browser ...

Issue with implementing autocomplete using AJAX and PHP for multiple input fields

HTML code: <table> <tr> <td align="center"> <label for="InputBox1"><b>~</b><font color="red">*</font>: &nbsp;</label> </td> </tr> <tr> <td align="center"> <div id="1"> ...

Recording the $index value of dynamically included inputs

Check out my Plunker demo: http://plnkr.co/edit/sm3r4waKZkhd6Wvh0JdB?p=preview I have a dynamic set of form elements that users can add and remove. I am looking to include an 'id' property for each object in the form elements, corresponding to ...

Unable to adjust the height of an MP4 video to properly display within a Material Box in both landscape and portrait orientations

While I have been learning JavaScript React, I encountered an issue with positioning an MP4 movie. You can view the code in this Codesandbox If you check out the FileContentRenderer.jsx file, you will see that the html5-video is used for the MP4. The g ...

What is the best way to implement a transaction fee when a specific function is triggered within my contract?

Consider this scenario: whenever a user successfully performs a contract function that calculates the sum of two numbers, I want to impose a 1% ETH fee that is transferred to a separate account from the contract. Although my current method "works", it is n ...