检查AngularJS中所需的复选框

时间:2018-04-09 09:51:24

标签: angularjs

我有一个主题列表,用于填充 一组复选框。我有一个SubjectIds列表, 其中,主题的值与主题ID匹配 将选中该复选框。

对于这个html代码是:

<div ng-repeat="subj in Subjects">
    <div ng-repeat="sub in SubjectIds">

        <input type="checkbox" ng-model="subjectModel[subj.SubjectId]" ng-checked="subj.SubjectId==sub"/>{{subj.SubjectName}}
    </div>
</div>

此代码检查所需的复选框,但复选框将按SubjectIds中的项目数重复。

2 个答案:

答案 0 :(得分:0)

您可以改为使用此代码:

<div ng-repeat="subj in Subjects">

    <input type="checkbox" ng-model="subjectModel[subj.SubjectId]" ng-checked="SubjectIds.indexOf(subj.SubjectId) != -1"/>{{subj.SubjectName}}

</div>

答案 1 :(得分:0)

您需要一个逻辑来检查索引是否在给定数组中。我建议你对数组使用.indexOf()方法。这是一个例子:

&#13;
&#13;
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.Subjects = [
  {"SubjectId":1,"SubjectName":"Name1"},
  {"SubjectId":12,"SubjectName":"Name12"},
  {"SubjectId":101,"SubjectName":"Name101"},
  ];

  $scope.SubjectIds = [1, 101];
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
  <div ng-repeat="subj in Subjects">
    <input type="checkbox" ng-model="subjectModel[subj.SubjectId]" 
      ng-checked="SubjectIds.indexOf(subj.SubjectId)!=-1"/> 
        {{subj.SubjectName}}
  </div>
</div>
&#13;
&#13;
&#13;