Search code examples
javascriptangularjsangular-filtersangular-componentsangular-controller

Angular Filter for returning true false from api?


So i am trying to display, weather a user is active or not active. The data comes via an api in Boolean form. So it will simply say user is true or user is false .I want to show 'Active' if data returns true, 'Not Active' if user return false.Solution i did was a simple if else that does the job, but this is heavily reused through out the app and i want to make an angular filter to do this task. I am a beginner in angular and java script and haven't created a filter before.

this is my if else and showing it in html this i how i want to use eventuatlly

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


Solution

  • For this you need to create filter. Try to with the given code
    
    <!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>