How to make checkboxes like radio buttons in ng-repeat?

I am facing the problem of using a checkbox as a radio button in ng-repeat. If you select and deselect a field, and only one check box is selected at a time. It works WITHOUT Ng-repeat. But I want to use this in ng-repeat.

Here is my HTML file:

<!DOCTYPE html>
<html ng-app="plunker">
    <head>
       <meta charset="utf-8" />
       <title>AngularJS Plunker</title>
       <script>document.write('<base href="' + document.location + '" />');</script>
       <link rel="stylesheet" href="style.css" />
       <script data-require="angular.js@1.1.x" src="http://code.angularjs.org/1.1.5/angular.min.js" data-semver="1.1.5"></script>
       <script src="app.js"></script>
    </head>
<body ng-controller="MainCtrl">
   <h1> WithOut ng-repeat </h1>
     <input type="checkbox" ng-checked="model1=='11'" ng-click="model1='11'"> a
     <br/>
     <input type="checkbox" ng-checked="model1=='12'" ng-click="model1='12'"> b
     <br/>
     <input type="checkbox" ng-checked="model1=='13'" ng-click="model1='13'"> c
     <br>
     Model = {{model1}}
  <h1> With ng-repeat </h1>
    <div data-ng-repeat="p in pp.rate">
       <input type="checkbox" ng-checked="model=='{{p.price}}'"  
          ng-click="model='{{p.price}}'"> 
        Model = {{model}}
    </div>
  </body>
</html>

      

Here is my controller:

var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
    $scope.pp = { 
      rate: [ {price: '11'},
              {price: '12'},
              {price: '13'}
      ]
     };
});

      

Here is My Plunker Link  http://plnkr.co/edit/BUHPNjTGaIsG33hsSWeC?p=preview

Please give me a solution in advance.

+3


source to share


2 answers


I had the same problem today and finally found a nice solution:

<div data-ng-repeat="p in pp.rate">
    <input type="checkbox" ng-model="result.price" ng-true-value="{{p.price}}" ng-false-value="" > 
    {{p.plan}}
</div>

      

plunkr demo http://plnkr.co/edit/qLlFBhnUdzTnAu1U71uk?p=preview



I hope this helps you or it helps others in the future

Good luck!

+12


source


The problem is that ng-repeat creates a new scope and you are not using notation dot

to reference your model.

See the updated plunkr here http://plnkr.co/edit/EQdv60ppdVm5Nkp2o8p8?p=preview



I added an object selection

that keeps track of the selection instead of the string value model

. Then the checkbox is checked opposite selection.model

instead ofmodel

It is highly recommended that you read https://github.com/angular/angular.js/wiki/Understanding-Scopes  to understand prototypal inheritance and scope impact.

+4


source







All Articles