dkc007 dkc007 - 14 days ago 6
AngularJS Question

Bind Value in ng-model through ng-repeat

I am not able to fetch value in my ng-model when checkbox is selected or not.

config.previewData[0] = {"Country":"Hong Kong","Level":0,"TonerQty":23166}


my html code like

<div ng-repeat="(key, val) in config.previewData[0]">

<label class="checkbox" for="{{$index}}">
<input type="checkbox" ng-model="config.Selectedkey[$index]" name="group" id="{{$index}}" />
{{key}}
</label>
</div>


but in
config.Selectedkey[$index]
nothing is bind when i click on check box.

Answer

Basically, when you use ng-repeat, it creates it own scope with in the repeat. So, when you want to access the parent scope / use the model which is inside the repeat, you need to use controller as syntax / use $parent.

I changed it to use ControllerAs syntax and it started working.

More about ng-repeat

var app = angular.module('sampleApp', []);

app.controller('MainCtrl', function($scope) {
  $scope.previewData = [{
    "Country": "Australia",
    "TonerQty": 4,
    "TonerQty1": 720
  }, {
    "Country": "Australia",
    "TonerQty": 1,
    "TonerQty1": 20839
  }, {
    "Country": "Australia",
    "TonerQty": 3,
    "TonerQty1": 639
  }, {
    "Country": "Australia",
    "TonerQty": 12,
    "TonerQty1": 36
  }, {
    "Country": "Australia",
    "TonerQty": 0,
    "TonerQty1": 0
  }, {
    "Country": "Australia",
    "TonerQty": 6,
    "TonerQty1": 396
  }, {
    "Country": "Australia",
    "TonerQty": 8,
    "TonerQty1": 24
  }, {
    "Country": "Australia",
    "TonerQty": 5,
    "TonerQty1": 495
  }, {
    "Country": "Australia",
    "TonerQty": 10,
    "TonerQty1": 180
  }, {
    "Country": "Australia",
    "TonerQty": 2,
    "TonerQty1": 1452
  }];

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<div ng-app="sampleApp">
  <div ng-controller="MainCtrl as mc">
    <div ng-repeat="(key, val) in previewData[0]">

      <label class="checkbox" for="{{$index}}">
        <input type="checkbox" ng-model="mc.Selectedkey[$index]" name="group" id="{{$index}}" />{{key}}
      </label>
    </div>
    {{mc.Selectedkey}}
  </div>
</div>

Comments