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.
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>
The problem is in if (value)
. This causes the return value === true ? ...
line to be processed only when the value is actually truthy (i.e. never for false
). You just need to construct the conditions properly:
function formatter (value) {
return (value === true) ? 'Yes' : ((value === false) ? 'No' : '');
}
A version with better readability:
function formatter (value) {
if (value === true) {
return 'Yes';
} else if (value === false) {
return 'No';
} else {
return '';
}
}
Edit: I haven't looked at your HTML. As another answer points out, using ng-model
for this is a bad idea, creating a filter should suit you just fine.