【问题标题】:ngRepeat and checkboxngRepeat 和复选框
【发布时间】:2016-02-23 19:47:40
【问题描述】:

我有一个带有 ng-repeat 的 div:

<div ng-repeat="fruit in fruits">
  <input type="checkbox" ng-model="this.value" ng-checked="false">{{fruit.code}} - {{fruit.short_name}}
</div>

这里的 furits 是数组对象,其中包含字段代码 short_name。

furits: {
         {
          code : code_value1,
          short_name :short_name_value1
         },
         {
          code : code_value2,
          short_name :short_name_value2
         },...
         {
          code : code_value..,
          short_name :short_name_value..
         },
       }

我想在提交按钮单击后获取选中复选框的代码并将这些代码插入新数组中。

并且还将相同的数组发送到服务器以完成任务。

请帮我解决这个问题。

【问题讨论】:

  • 请在此处添加您的网络服务以将数组发送到服务器

标签: angularjs checkbox ng-repeat


【解决方案1】:
<div ng-repeat="fruit in fruits">
  <input type="checkbox" ng-model="fruit.isSelected" />{{fruit.code}} - {{fruit.short_name}}
</div>
<input type="button" ng-click="sendServer()" value="Submit" />

你的控制器方法就像,

 $scope.sendServer = function(){
  $scope.checkedFruits = [];
  for(i = 0; i < $scope.fruits.length; ++i){
    if ($scope.fruits[i].isSelected)
        $scope.checkedFruits.push(fruit.code);
  }
  $scope.postData();
 }

//Send array to server via web service with parameter FruitsCode

 $scope.postData = function () {
   $http.post('http://your.webservice/', {FruitsCode:$scope.checkedFruits}).success(
    function(data){
        $scope.response = data
    })

}

希望对您有所帮助!

【讨论】:

  • 谢谢你们。但是,这一行:“$scope.fruits[i].isSelected”返回“未定义”...
  • 请更改视图 ng-model="fruit.isSelected"
  • 请添加默认值为 false 的 isSelected 字段数组对象水果
  • 你说得对……我把它改成了“fruit.isChecked”(就是在这里写的)。现在它开始工作了!谢谢你。这两个选项有什么不同?
  • angular js 有两种方式从控制器绑定到视图和视图到控制器
【解决方案2】:
<div ng-repeat="fruit in fruits">
  <input type="checkbox" ng-model="fruit.isChecked" />{{fruit.code}} - {{fruit.short_name}}
</div>
<input type="button" ng-click="save()" value="SAVE" />

在你的控制器内部:

$scope.save = function(){
    var myFruits = [];
    for(i = 0; i < $scope.fruits.length; ++i){
        if ($scope.fruits[i]. isChecked)
            myFruits.push(fruit.code);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-22
    • 1970-01-01
    • 1970-01-01
    • 2015-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-31
    相关资源
    最近更新 更多