AngularJS Live Example
by vojtajina
HTML
<div ng-app="zg" ng-controller="MyController">
value = {{business.attachment.has_air_conditioning}}<br>
set to <a ng-click="business.attachment.has_air_conditioning = true">true</a> <a ng-click="business.attachment.has_air_conditioning = false">false</a>
<div boolean-radio-model ng-model="business.attachment.has_air_conditioning" zg-true-label="Yes" zg-false-label="No"></div>
</div>
CSS
</style>
<script src="http://docs-next.angularjs.org/angular-1.0.0rc2.min.js"></script>
<style>
.ng-invalid { border: 1px solid red; }
body { font-family: Arial,Helvetica,sans-serif; }
body, td, th { font-size: 14px; margin: 0; }
table { border-collapse: separate; border-spacing: 2px; display: table; margin-bottom: 0; margin-top: 0; -moz-box-sizing: border-box; text-indent: 0; }
a:link, a:visited, a:hover { color: #5D6DB6; text-decoration: none; }
.error { color: red; }
JavaScript
angular.module('zg', []).
directive('booleanRadioModel', function() {
return {
require: 'ngModel',
scope: {
zgTrueLabel: 'attribute',
zgFalseLabel: 'attribute'
},
template:
'<div>' +
'{{zgTrueLabel}} <input type="radio" name="some" value="true">' +
'{{zgFalseLabel}} <input type="radio" name="some" value="false">' +
'</div>',
link: function(scope, elm, attr, ctrl) {
var inputs = elm.find('input');
// view -> model
elm.bind('click', function(e) {
if (e.target.nodeName.toLowerCase() !== 'input') return;
scope.$apply(function() {
ctrl.$setViewValue(e.target.value === 'true');
});
});
// model -> view
ctrl.$render = function() {
inputs[0].checked = ctrl.$viewValue;
inputs[1].checked = !ctrl.$viewValue;
};
}
};
});
function MyController($scope) {
$scope.business = {
attachment: {
has_air_conditioning: true
}
};
}