【问题标题】:ng-repeat with checkboxes and capture value带有复选框和捕获值的 ng-repeat
【发布时间】:2014-10-02 12:16:12
【问题描述】:

仍然是 Angular 和 js 的新手。我有一个清单:

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

当用户点击它们时,我希望将值推送到列表中:

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

但我想像这样将一个键值对附加到 fastrates:

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

我想我被困在控制器中的 ng-change 函数上来处理这个问题。我知道这远未完成,但至少价值发生了变化。我需要检查它是否已添加,如果已添加,则将其从对象中的键、值中删除。如果它没有被检查,他们会检查它。它需要在 fastrates obj 中创建一个新的“值”:速率对。

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

这是我开始的一个 plnkr http://plnkr.co/edit/MhqEp7skAdejdBRpXx2n?p=info。有关如何完成此操作的任何脚本建议?

【问题讨论】:

  • fastrates 应该是对象还是值数组?

标签: angularjs checkbox ng-repeat


【解决方案1】:

您不能多次使用同一个密钥。您可以使用对象数组。

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

取消选中复选框时不要忘记删除值。

【讨论】:

  • 啊哈。谢谢,我脑残了这些数据被发送到 XML 中,所以我想我必须重复相同的键......
【解决方案2】:

http://plnkr.co/edit/MhqEp7skAdejdBRpXx2n?p=preview 取消选中复选框时从数组中删除值

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


  }
});

【讨论】:

    猜你喜欢
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    • 2015-08-29
    • 2015-05-14
    • 2014-08-24
    • 2013-08-11
    • 2016-09-29
    • 1970-01-01
    相关资源
    最近更新 更多