snowflakes74 snowflakes74 - 2 months ago 7
AngularJS Question

How to get input value from ng-repeat in Angular

I am trying to do a simple shopping cart in angular. Basically I have list of items and would like user to enter Quantity and then get the list of items that have Qty more than 0.

If the Qty is greater than 0 then I will add them into an array otherwise remove it.

I must be doing something wrong that is preventing me to get the Qty correct.

It works only first time but the second time it does not update.

My controller:

var extras1 = {Id:1,PackageName:"Balloons",Description:'Pack of 6',Cost:'$50.00',Qty:0}
var extras2 = {Id:2,PackageName:"Hot Chips",Description:'Fresh fried hot chips fully of yummy fat and cholesterol.',Cost:'$10.00',Qty:0}
var extras3 = {Id:3,PackageName:"Sausages",Description:'Hot sausages from premium offcuts',Cost:'$10.00',Qty:0}

$scope.extras =[extras1,extras2,extras3];

$scope.extraSelected = function(){
$scope.selectedExtra =[];
angular.forEach($scope.extras, function(extra)
{
if(extra.Qty > 0 )
{
console.log('Extra added');
$scope.selectedExtra.push(extra);
}


})
console.log($scope.selectedExtra);
}


Markup :

<div ng-repeat="extra in extras" class="text-left">
<div class="row-centered">
<div class="row form-group">
<label class="col-md-1 col-sm-offset-1 step1-question" >{{$index + 1}}</label>
<div class="col-md-8">
<span class="h4 step1-answer"> {{ extra.PackageName}} </span>
<br/>
<span class="h5"> {{ extra.Description}} </span>
<br/>
<span class="h5"> {{ extra.Cost}} </span>
</div>
<div class="col-md-1">
<input type='text' class="form-control step1-answer text-center "
ng-model="extra.Qty"
placeholder="0" style="background-color:#ffffff;padding: 5px;height: 45px;"
ng-change="extraSelected(extra)"
/>
</div>
</div>
<hr/>
</div>
</div>

Answer

Maybe something, like this?

<input type="number" ng-model="extra.Qty" ng-change="extraSelected()">

$scope.extraSelected = function () {
        $scope.selectedExtra = [];
        angular.forEach($scope.extras, function(extra) {
           if(extra.Qty > 0) {
               console.log('Extra added');
               $scope.selectedExtra.push(extra);
           }
        })
        console.log($scope.selectedExtra);
    }