无法从Checkbox获取ID

时间:2017-09-06 12:16:45

标签: javascript jquery angularjs

我有HTML复选框,它们的id是从角度ng-repeat生成的,当我尝试收集id来使用它时,它总是以未定义的形式返回。

$("input:checkbox.time-check-input").each(function () {
    var ruleUnformatted = "";
    var checked = $(this);
    if (checked.is(":checked")) {
        ruleUnformatted = checked.id;
        var name = "Rule" + count;
        settingsObj[name] = ruleUnformatted;
        count++;
    }  
}); 

HTML:

<div class="time-check">
    <input type="checkbox" value="None" ng-click="settings.checked($event)" class="time-check-input" id="{{level.LevelTmsCode}}-{{day.Day}}-open" name="check"/>
    <label for="{{level.LevelTmsCode}}-{{day.Day}}-open" class="time-check-input"></label> <span>Open</span>
</div>

我知道有时可以在vanilla代码之后加载角度,但我认为这不是问题,因为这个代码是通过按下按钮启动的。此外,在Chrome中进行调试时,我可以看到ID,但出于某种原因,选择它无效。

1 个答案:

答案 0 :(得分:1)

你的方法完全错了。 ,这是一个使用纯角度的例子。

(function(angular) {
  'use strict';
  angular.module('myApp', [])
    .controller('Controller', ['$scope', function($scope) {
    
      //Create array to hold settings
      $scope.settings = [];
      for (var i = 0; i < 10; i++) {
        $scope.settings.push({
          text: "setting" + (i + 1),
          checked: false
        })
      }

      $scope.showChecked = function() {
        var arr = $scope.settings.filter(function(x) {
          return x.checked;
        }).map(function(x) {
          return x.text
        });
        console.clear()
        console.log(arr)
      }
    }]);
})(window.angular);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="Controller">

    <div class="time-check" ng-repeat="setting in settings">

      <label class="time-check-input">
    <input type="checkbox" ng-change="showChecked()" ng-model="setting.checked" name="check"/> {{setting.text}}
    </label>

    </div>

  </div>
</div>