如何从Angular中的ng-repeat获取输入值

时间:2016-09-27 10:56:13

标签: javascript angularjs

我正试着用角度做一个简单的购物车。基本上我有项目列表,并希望用户输入数量,然后获取数量超过0的项目列表。

如果数量大于0,那么我会将它们添加到数组中,否则将其删除。

我必须做错事,这会妨碍我让数量正确。

它仅适用于第一次,但第二次不会更新。

我的控制器:

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

加价:

 <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>

2 个答案:

答案 0 :(得分:1)

也许是这样的东西?

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

答案 1 :(得分:0)

 $scope.extraSelected = function(extra){
    $scope.selectedExtra =[];
    angular.forEach($scope.extras, function(extra)

你有额外的定义作为传入的参数,也作为forEach函数的参数 - forEach循环遍历数组,Qty为0,所以它总是为零。

更改其中一个功能参数,使其不会破坏另一个。

功能范围的教训......