Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 a user clicks on them, i'd like the value to be pushed to a list:

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

But I'd like to append a key, value pair to the fastrates like this:

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

I guess i'm stuck on my ng-change function in my controller to handle this. I know this is far from complete but at least the value changes. I need to make it check if it has been added and if so then remove it from the key, value from the object. If it's unchecked and they check it. It needs to create a new 'value': rate pair in the fastrates obj.

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

Here's a plnkr I started http://plnkr.co/edit/MhqEp7skAdejdBRpXx2n?p=info. Any scripting advice on how to accomplish this?

like image 714
Garuuk Avatar asked May 26 '26 17:05

Garuuk


2 Answers

You can't use same key multiple times. You can use array of object.

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 });
  }
});

Don't forget to remove value when you uncheck the checkbox.

like image 80
Darshan P Avatar answered May 30 '26 09:05

Darshan P


http://plnkr.co/edit/MhqEp7skAdejdBRpXx2n?p=preview removing value from array when you uncheck checkbox

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);
    }


  }
});
like image 24
sylwester Avatar answered May 30 '26 11:05

sylwester