Reputation: 1975
How do I define a checkbox in an angular form that is checked when the model evaluates to true (anything like "yes", "1", 1,...) and is unchecked when the model evaluates to false ("0", 0, undefined, ...)? I get the data from a rest service and the represantation of true and false can vary. If the user changes the value in the form it should be set to "1" (on) or "0" (off). If he changes it again it should be set to it's original value and marked as unchanged. I'd like to write markup like:
<input type="checkbox" ng-model="value1" my-custom-directive>
<input type="checkbox" ng-model="value2" my-custom-directive>
Upvotes: 0
Views: 6687
Reputation: 1975
It seems that there is no easy way to do this with a directive, so I alter my model after the http request:
value = value ? true : false;
The form is then simple:
<input type="checkbox" ng-model="value">
When the user submits the form there will be some transformation like:
if (value && ! oldvalue || ! value && oldvalue) {
value = value ? 1 : 0;
// send http request
} else {
// nothing to do
}
Upvotes: 0
Reputation: 2053
Ok, I just finish the case on jsfiddle
All the stuff is do by a simple filter that evaluates the truffy values you defined ;-)
angular.module('App', [])
.filter('isTruffy', function () {
return function (input) {
// Add here, how much truffy values as you want, this is not case sensitive...
var truffies = [1, '1', true, 'true', 'yes', 'y'];
if (typeof input == 'String')
input = input.toLowerCase();
return truffies.indexOf(input) > -1;
};
});
After, just call your filter on your template
<input type="checkbox" ng-checked="b | isTruffy" />
Upvotes: 2
Reputation: 89
Please add the below function in controller in ng-checked.
$scope.validateColName = function (colname) {
var url = $scope.url;
$http.get(url)
.success(function (data) {
if(data){
$scope.checkvaluecol= 'true';
}else{
$scope.checkvaluecol= 'false';
}
})
.error(function(data, status, headers) {
$scope.handleErrorInDialogs(status);
});
};
and this to your input tag which is od type checkbox.
ng-checked="checkIndicator(checkbox1)"
Upvotes: -1