Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ng-model's attribute in a ng-repeat input checkbox gets always literal or give error

So i need to know the extras of a car than a user wants to include in his preferences. I'm trying to create input checkboxes from an array obtained by an ajax request and generate the inputs by ng-repeat. The major objective is to know the checkboxes selected by the user. I'd like that my approach to be create an auxiliar array which contains the selected ones, but i don't know how to set a unique ng-model to every item in the ng-repeat iteration so i can know the list of selected items. I guess there is something left in my knowlege of angular. Here is what i have for now..

In the controller...

$http.get('/ajax/ajax_get_extras/'+$scope.car.version+'/false').success(function(data) {
                $scope.extras = data;
         });  
$scope.addExtra = function(){ // ... manage the auxiliar array }

In the html ...

<div ng-controller="Controller">
        <form novalidate class="simple-form">
            <span ng-repeat="extra in extras">
                <input  type="checkbox" ng-model="extra.id" ng-change="addExtra()" name="extra_{{extra.id}}" >{{extra.name}} - <strong>{{extra.real_price | onlynumber | currency}}</strong>
            </span>
        </form>
</div>

And i'm stuck since the extra.id doesnt transform to the real extra.id and stays as a string "extra.id" >_<

I tried extra_{{extra.id}}, extra.id, {{extra.id}}, $index as posibles ng-model and none works.

like image 811
R01010010 Avatar asked Jul 22 '13 12:07

R01010010


1 Answers

In AngularJS 1.1.5 there is "track by" that you can use in ngRepeat.

So you can:

 <input type="checkbox" ng-repeat="e in extra track by $index" ng-model="extra[$index]">

Here is a example: http://plnkr.co/edit/6lNo6R5EPsNGHUU6ufTE?p=preview

like image 194
Valentyn Shybanov Avatar answered Sep 17 '22 23:09

Valentyn Shybanov