How to use an Angular filter to extract boolean values from an API response?

I am currently working on a feature to display whether a user is active or not based on data retrieved from an API in Boolean form. The API returns 'true' if the user is active and 'false' if not. To achieve this, I initially implemented a simple if-else statement which served its purpose. However, considering its frequent usage across the application, I have decided to create an angular filter to handle this task more efficiently. As a beginner in Angular and JavaScript, creating a filter is new territory for me.

This is how I currently implement the if-else logic in HTML:

<label>{{ $ctrl.myValu | truefalse}}</label>

  $onInit = () => {
        let self = this;

        this.siUser.current().then((userData) => {
            let actingAsTenant = userData.user.apikey;

            if (actingAsTenant) {

                self.siTenant.current().then((tenant) => {
                    self.tenant = tenant;
                   
                   ///starts
                    if (self.tenant.active == true) {
                        self.tenant.active = 'Active'
                    }
                    else if (self.tenant.active == false){
                        self.tenant.active = 'Not Active'
                    }
                    //end
                    
                }, (err) => {
                    self.siAlertDialog.error(err.data.message)
                })

            }
        }, (err) => {
            self.siAlertDialog.error('Error rendering tenant details');
        });
    }
<strong>{{$ctrl.tenant.active}}</strong>

Answer №1

To achieve this functionality, you will need to set up a filter using the provided code snippet:

<!DOCTYPE html>
    <html lang="en">
    <head>

        <title>Ristorante Con Fusion: Menu</title>
          <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
    </head>
    <body>

      <div ng-app="myapp" ng-controller="userController" >
      {{ myValu | truefalse }}

        <script>
   var app = angular.module('myapp', []);

   app.filter('truefalse', function(){
        return function(text){
          return text ? "Active" : "Not Active";
        }
      })
app.controller('userController', function($scope) {
      $scope.myValu = true;
});
        </script>
    </body>
    </html>

Answer №2

One way to handle this is using the Ternary Operator:

JavaScript Example

///starts
      condition ? 'Outcome if true' : 'Outcome if false';
//end

OR

In an Angular Expression

<strong>{{ $ctrl.tenant.active ? 'Active' : 'Not Active' }}</strong>

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

Taking a closer look at an observable in Ionic 2 before passing it along

As someone who is new to Ionic and Angular, with years of experience in .NET development, I am currently experimenting with building a login prototype using Ionic 2. One of the examples I found online involves integrating WebAPI that returns JSON data indi ...

Nextjs server encountered an issue where it was unable to connect to the localhost

npm run dev > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="563239352239247b372626393f38223b3338227b3439393d3f38317b2133347b372626166678677866">[email protected]</a> dev > next dev ▲ Next.js 14.2. ...

The KoGrid filter is malfunctioning when used in conjunction with Plunker

I'm currently facing an issue with the filter functionality on the knockoutjs ko grid. There are a couple of issues that I've encountered: Firstly, the drop-down menu for the filters displays "Choose columns" but the column names get cut off at ...

My findOne() function seems to be malfunctioning - could there be an issue with my syntax?

I have created a database called 'rodrigo-contatos' using the following code: var mongojs = require('mongojs'); var db = mongojs('rodrigo-contatos', ['rodrigo-contatos']); In an attempt to search the database, I am ...

Vue-Apollo - The 'value' property is not present in the 'Readonly<Ref<Readonly<any>>>' type

MY CURRENT DILEMMA: In my quest to seamlessly integrate vue-apollo v4 with Typescript, I have encountered a challenge. I am in the process of retrieving data from a simple query using useQuery along with useResult. The default return type of useResult i ...

Steps to implement provided information in a post within the header of a webpage

Recently, I started creating websites from scratch and I encountered a problem that I could use some help with. The issue is when I have a YouTube video embedded in a post, but I want to showcase the video in the header section of that specific post URL wi ...

Angular offers a range of search filters for optimizing search results

The system currently has 3 search fields: 1. Name.... 2. Subject.... 3.Price.... Each of these filters works independently - when searching by name, only results matching that name are displayed; similarly for subject and price. However, the challeng ...

Which is better: Using AngularJS with Express Templates or sticking with pure HTML? An analysis of the

Express JS utilizes templates to generate HTML which is then sent from the server to the client in response. There are various templates available for generating HTML, some of which include: Jade () EJS () In my application, I need to incorporate bo ...

Angular factory functions that include .success and .error methods

I am new to using Angular and I'm curious about the recommended best practices for placing the .success and .error functions. Should they be within the controller or within the factory? Here are two examples: Option 1: (function(){ 'use str ...

What is the method for launching a new tab within an incognito window that is already open?

In the process of developing a Chrome extension, I am focusing on the functionality of creating a new tab from context menus within an incognito window. My current approach involves using the following script: chrome.windows.create({url: "https://google.c ...

"Error: The .cssText method in Javascript is not working properly

I have been encountering an issue where the .cssText is not updating the HTML element referred to as .unveil. I implemented an event that when the container for .unveil is clicked, the .unveil element should become visible. However, upon clicking the .unve ...

Implementing Partial Login and Registration Views using AngularJS in conjunction with MVC5 and ASP.NET Identity

Embarking on the journey of creating a Single Page Application with log-in/register functionality using MVC5, ASP.NET Identity, and Angular feels like diving into a vast ocean of web development technologies. Despite being new to this realm, I delved into ...

Page loading causing sluggishness in Angular application

I've been encountering this problem for quite some time now and have searched extensively online for solutions. However, I believe I may not be using the correct terminology to accurately pinpoint the issue. Within my package.json, I have included th ...

Changing the value of a specific array element after removing it from a filtered ng-repeat resultList

I have a list of users where you can select a user by clicking on it, which then places the selected element into an object called $scope.selectedMember. The ng-repeat directive is being used along with a filter in a search box. It's crucial that $sco ...

AngularJS fails to trigger window scroll event

Although I have come across similar inquiries regarding this issue, none of the solutions have proven to be effective for me. Currently, I am working with AngularJS and I am attempting to detect the scroll event. Despite trying numerous variations to capt ...

Next.js 14 useEffect firing twice upon page load

Having an issue with a client component in next js that is calling an API twice at page load using useEffect. Here's the code for the client component: 'use client'; import { useState, useEffect } from 'react'; import { useInView ...

Achieving asynchronous results in the parent function with TypeScript: a guide

The code structure provided is as follows: import {socket} from './socket'; class A{ Execute(...args[]){ //logic with Promises SomeAsyncMethod1().then(fulfilled1); function fulfilled1(){ SomeAsyncMethod2(args).then(fulfilled2); ...

What is the best method for inserting the HTML content from a specific div into a textarea?

Everything seems to be working fine, but once I insert the HTML into the textarea, an issue arises where the div gets wrapped within another div, causing the layout to break. var urls = []; $('body').on('click', '.btn_video&apos ...

JavaScript - Transforming Name:ItemName/Value:ItemValue Pairs into Standard ItemName:ItemValue JSON Format

Looking to reformat JSON data? [{"name":"age","value":31}, {"name":"height (inches)","value":62}, {"name":"location","value":"Boston, MA"}, {"name":"gender","value":"male"}] If you want it to be in a different format: [{"age": 31}, {"height (inches)": 6 ...

Here are the steps to pass the selected dropdown value to ng-repeat for ordering:

I have a dropdown box with options for filtering data in an ng-repeat by different criteria. How can I pass the selected value from the dropdown to the ng-repeat orderby? Here is my dropdown: <select name='filter_range' id='filter_range ...