• Ng-repeat with checkboxes and capture value

    Still new to angular and js. I have a list:

    <ul ng-repeat="rate in resources">
        <li> <input type="checkbox" ng-model="isSelected" ng-change="appendList(rate)"> </li>
    </ul>
    
          

    When the user clicks on them, I want the value to be clicked into the list:

    $scope.rateValues = {
        'rates': {
            'fastrates': {
                'value': '',
            }
        }
    };
    
          

    But I would like to add a key and value pair for speeds like this:

    $scope.rateValues = {
        'rates': {
            'fastrates': {
                'value': '100',
                'value': '200',
                'value': '300',
                'value': '400',
            }
        }
    };
    
          

    I think I am stuck on my ng-change function in my controller to handle this. I know this is far from complete, but at least the meaning is changing. I need to check if it is added, and if so, remove it from the key, value from the object. If it is not installed and they check it. It needs to create a new "value": rate pair in the fastrates objects.

      $scope.appendList = function(rate){
          $scope.rateValues.rates.fastrates.value = rate
       }
    
          

    Here is plnkr I started http://plnkr.co/edit/MhqEp7skAdejdBRpXx2n?p=info . Any scripting advice on how to do this?

    +3


    source to share


    2 answers


    You cannot use the same key multiple times. You can use an array of objects.

    var app = angular.module('plunker', []);
    
    app.controller('MainCtrl', function($scope) {
    
      $scope.resources = {value:['100','200','300', '400']}
    
        $scope.rateValues = {
            'rates': {
                'fastrates': []
            }
        };
    
      $scope.appendList = function(rate){
          $scope.rateValues.rates.fastrates.push({ value: rate });
      }
    });
    
          



    Remember to remove the value when unchecking the checkbox.

    +2


    source


    http://plnkr.co/edit/MhqEp7skAdejdBRpXx2n?p=preview removing value from array on unchecking



    var app = angular.module('plunker', []);
    
    app.controller('MainCtrl', function($scope) {
    
      $scope.resources = {
        value: ['100', '200', '300', '400']
      }
    
    $scope.rateValues = {
        'rates': {
            'fastrates': {
                'value': [],
            }
        }
    };
      $scope.appendList = function(rate) {
    
    
    
        var index = $scope.rateValues.rates.fastrates.value.indexOf(rate);
    
    
        if (index < 0) {
          $scope.rateValues.rates.fastrates.value.push(rate);
        } else {
    
          $scope.rateValues.rates.fastrates.value.splice(index, 1);
        }
    
    
      }
    });
    
          

    +1


    source







    All Articles