Amin Uddin Amin Uddin - 10 months ago 88
AngularJS Question

Convert boolean value to yes/no by angular directive

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

function () {
return {
restrict: 'EA',
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
function formatter(value) {
if (value) {
return value === true ? 'Yes' : 'No';
} else {
return '';


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

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

Answer Source

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

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