6

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.

0

3 Answers 3

14

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="-">
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

1

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 ? '+' : '-';
};

2 Comments

Just a reminder: You don't need to set initial value for $scope.isChecked variable. Angular will evaluate as false, unless you want to force to be created as true. And it's always a good idea to avoid $watch expressions, especially in large scale apps or when you have options to do without using $watch. =)
Correct. I just put that in there to demonstrate how you could initially set the value of the checkbox.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.