Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular.js. Ng-model of checkbox

Tags:

angularjs

Here's my code:

<input type="checkbox" ng-model="variable">

In this case variable will be true or false according the status of checkbox. I need to set not true/false but "+"/"-" instead. What is the simplest way to do this? Thanks.

like image 644
Fyodor Khruschov Avatar asked Oct 30 '13 19:10

Fyodor Khruschov


3 Answers

According to the docs, you should use ng-true-value and/or ng-false-value to override true and false values:

<input type="checkbox" ng-model="variable" ng-true-value="+" ng-false-value="-">
like image 137
Blazemonger Avatar answered Oct 18 '22 02:10

Blazemonger


Use ng-click to do that.

<input type="checkbox" ng-model="variable" ng-click="check()">

In the controller :

$scope.check = function() {
    $scope.selected = $scope.variable === true ? '+' : '-';
};

Live Plunker.

like image 29
Deividi Cavarzan Avatar answered Oct 18 '22 02:10

Deividi Cavarzan


Just setup a watch on your checkbox model.

HTML:

<input type="checkbox" ng-model="isChecked">

JavaScript:

// set initial value
$scope.isChecked = $scope.variable === '+';

// watch for changes to the checkbox model
$scope.$watch('isChecked', function(newVal) {
    $scope.variable = newVal ? '+' : '-';
};
like image 1
Brian Lewis Avatar answered Oct 18 '22 02:10

Brian Lewis