Masinde Muliro
Masinde Muliro

Reputation: 1183

Binding dynamic checkbox in angular.js

I have a list of options pulled from the database via json based on product selection in angular.js

Here's a sample code:

<ion-checkbox ng-repeat="extra in extras" ng-model="order.extras" checklist-value="{{ extra.id }}"><strong>{{ extra.name }}</strong></ion-checkbox>

I want a user to be able to select multiple extras but can't seem to be able to bind these selections.

Upvotes: 0

Views: 356

Answers (1)

AWolf
AWolf

Reputation: 8990

I think it could work with ng-model="order.extras[extra.id]" then you can track the checked extras in order.extras.

Please have a look at the demo below or at this jsfiddle.

angular.module('demoApp', ['ionic'])
	.controller('mainController', mainController);
    
function mainController($scope) {
	$scope.order = {};
	$scope.extras = [
    	{
        id: 0,
        name: 'first'
        },
        {
        id: 1,
        name: 'second'
        },
        {
        id: 2,
        name: 'third'
        }
    ]
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/ionic/1.2.4/css/ionic.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ionic/1.2.4/js/ionic-angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ionic/1.2.4/js/ionic.bundle.js"></script>
<div ng-app="demoApp" ng-controller="mainController">
<ion-content>
    <ion-checkbox ng-repeat="extra in extras" ng-model="order.extras[extra.id]" checklist-value="{{ extra.id }}"><strong>{{ extra.name }}</strong></ion-checkbox>
    
current order: {{order}}
    
</ion-content>
</div>

Upvotes: 1

Related Questions