Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert boolean value to yes/no by angular directive

Tags:

angularjs

I need to show Boolean value to yes/no using directive. My directive is given below

 directives.directive('niBooltoYesno',
        function () {
            return {
                restrict: 'EA',
                require: 'ngModel',
                link: function (scope, element, attrs, ngModel) {
                    function formatter(value) {
                        if (value) {
                            return value === true ? 'Yes' : 'No';
                        } else {
                            return '';
                        }
                    }
                    ngModel.$formatters.push(formatter);

                }
            };
        });

<ni-boolto-yesno data-ng-model="set_unit.isActive" ></ni-boolto-yesno>

But it does not work. Please help me in this point.

like image 302
Amin Uddin Avatar asked Nov 23 '14 10:11

Amin Uddin


People also ask

How do you change a Boolean to a yes or no?

Use the Yes/No data type to store a Boolean value, such as True or False, On or Off, Yes or No, and any field that contains only one of two values. This data type often maps to a Check Box control on a form or report.

Is Boolean yes or no?

Remarks. Use the Boolean Data Type (Visual Basic) to contain two-state values such as true/false, yes/no, or on/off. The default value of Boolean is False . Boolean values are not stored as numbers, and the stored values are not intended to be equivalent to numbers.

How do you convert a number to true?

"Conversion" means converting false to 0 and true to 1 1.


2 Answers

You're not using the right tool for the job. This should be a filter:

{{ someBooleanValue | yesNo }}

The filter would be as simple as

module.filter('yesNo', function() {
    return function(input) {
        return input ? 'yes' : 'no';
    }
});

If you still choose to use a directive, you don't need ngModel and formatters, which is used on form fields that must read and write to a model. All you need is a template:

module.directive('yesNo', function() {
    return {
        template: '<span>{{ yesNo ? "yes" : "no" }}</span>',
        scope: {
            yesNo: '='
        }
    };
});

and you woud use it as

<span yes-no="someBoolean"></span>
like image 132
JB Nizet Avatar answered Sep 28 '22 17:09

JB Nizet


I define textual values for 0 and 1 with...

{{object.PROPERTY?'Yes':'No'}}

...when presented with something like this:

{
  "PROPERTY": 0
}

The result would then be 'No'.

like image 20
Steven Ventimiglia Avatar answered Sep 28 '22 16:09

Steven Ventimiglia