Sudhakar
Sudhakar

Reputation: 3094

Checkbox value changes to true/false after click

I'm building form fields (checkboxes and dropdown) dynamically based on the values in a model $scope.config.kind. I'm setting the model names for each checkboxes dynamically based on the value in the model. The form is created fine, but when I select/check the check box its value change to true and false. How do I make its label not change when selected/unselcted?

 <div class="col-md-1">
            <div class="form-group">
                <label class="sm">Kind</label>
                <ul class="list-inline">
                    &nbsp;
                    <li ng-repeat="kind in config.kind">
                        <div class="checkbox">   
                            <label class="xsm-label">
                                <input type="checkbox" name="kind" ng-model="kind" ng-value="{{kind}}">&nbsp;{{kind}}
                            </label>
                        </div>
                    </li>
                </ul>    
            </div>

enter image description here

Upvotes: 1

Views: 4440

Answers (2)

Mike
Mike

Reputation: 1246

You need to use a different variable for the ng-model vs. the ng-value, as you're overwriting the value with the selected value of true/false. There are a few ways to do this, but bottom line is that you have to have some other data structure to receive the true/false values.

Consider making your list an object, like:

  $scope.config = { kinds: [
                        {name:'Bug', selected: false},
                        {name:'Task', selected: false},
                        {name:'RFE', selected: false},
                        {name:'Other', selected: false}
                        ]}

so that the "selected" values can be changed. see plunker here: http://plnkr.co/edit/O4qL2hB2El6eB6P96XfE

Upvotes: 1

marian2js
marian2js

Reputation: 819

The issue is because you are using the same variable to store the kind's name and the value. ng-model on a checkbox will set you variable to true or false. The solution is to have an object for each kind:

$scope.config.kind = [{
  name: 'Bug',
  value: false
}, {
  name: 'Task',
  value: false
}, {
  name: 'RFE',
  value: true
}, {
  name: 'Other',
  value: false
}];

Now you can refactor your view to looks like:

 <div class="col-md-1">
        <div class="form-group">
            <label class="sm">Kind</label>
            <ul class="list-inline">
                &nbsp;
                <li ng-repeat="kind in config.kind">
                    <div class="checkbox">   
                        <label class="xsm-label">
                            <input type="checkbox" name="kind" ng-model="kind.value" ng-value="{{kind.value}}">&nbsp;{{kind.name}}
                        </label>
                    </div>
                </li>
            </ul>    
        </div>

Upvotes: 2

Related Questions