【问题标题】:How to get collection of ng-model Checkbox in AngularJs?如何在 AngularJs 中获取 ng-model 复选框的集合?
【发布时间】:2015-08-27 02:16:15
【问题描述】:

这是我的数据:

var fields = [
  {id: 1, name: 'Model'},
  {id: 2, name: 'Price'},
  {id: 3, name: 'Condition'},
  {id: 4, name: 'Ads Type'}
];

这是我的视图代码:

 <ion-checkbox ng-repeat="field in fields"
               ng-model="field.id"
               ng-checked="field.id">
               {{ field.name }}
 </ion-checkbox>
 <button class="button button-positive" ng-click="updateField()">
    Update SubCategory Field
 </button>

这是我的控制器代码

$scope.updateField = function(){
   // How can I get an Array of any Checked rows 
   // Expected result is: [2, 4]
}

我试过这个:

console.log($scope.field.id);

和错误通过

Cannot read property 'id' of undefined

任何帮助将不胜感激。

干杯

【问题讨论】:

  • 你把console.log语句放在哪里?
  • 您不应使用var fields = [...],而应使用$scope.fields = [...]。然后您访问您的字段,例如$scope.fields[INDEX].checked
  • 我已经将控制台日志放在函数中,它只是一个示例数组,这就是它被填充到复选框中的原因。我只想在点击按钮后找回它。
  • 用“field.id”而不是'ng-model="field.checked"'映射ng-model
  • 你的“字段”中不应该有一个“已检查”的属性吗?

标签: javascript angularjs checkbox ionic


【解决方案1】:

http://plnkr.co/edit/lOSaa9k7EEpgriz4AmaZ?p=preview

HTML

<!DOCTYPE html>
<html ng-app="app">

<head>
  <script   src="https://code.angularjs.org/1.3.9/angular.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body>
  <h1>Hello Plunker!</h1>
  <div ng-controller="ctrl ">

   <input type="checkbox" ng-repeat="field in fields"
               ng-model="field.checked"
               ng-checked="field.checked">
               {{ field.name }} 
 </input>
 <button class="button button-positive" ng-click="updateField()">
    Update SubCategory Field
 </button>


          {{ selectedItems  | json }} 
  </div>
</body>

</html>

JS

var app = angular.module("app", [])

app.controller('ctrl', function($filter, $scope){

 $scope.fields = [
  {id: 1, name: 'Model'},
  {id: 2, name: 'Price'},
  {id: 3, name: 'Condition'},
  {id: 4, name: 'Ads Type'}
];

$scope.updateField = function(){

    var p = [];
    for (var i = 0; i < $scope.fields.length; i++) {
       var item = $scope.fields[i];
       if ( item.checked) {
        p.push(item )  
       }

    }

    $scope.selectedItems = p;
}

});

【讨论】:

  • 谢谢,我很嫉妒现在不是一个伟大的程序员。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-13
  • 2016-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多