我有一些复选框: -
<label>CHANNELS</label>
<md-checkbox ng-model="channel[0]" class="md-primary md-hue-2" ng-checked="selected.indexOf(channel[0]) > -1" ng-click="toggleSelection(channel[0])" value="channel[0]">CHANNEL A</md-checkbox>
<md-checkbox ng-model="channel[1]" class="margin-left-1 md-primary md-hue-2" ng-checked="selected.indexOf(channel[1]) > -1" ng-click="toggleSelection(channel[1])" value="channel[1]">CHANNEL B</md-checkbox>
<md-checkbox ng-model="channel[2]" class="margin-left-1 md-primary md-hue-2" ng-checked="selected.indexOf(channel[2]) > -1" ng-click="toggleSelection(channel[2])" value="channel[2]">CHANNEL C</md-checkbox>
<md-checkbox ng-model="channel[3]" class="margin-left-1 md-primary md-hue-2" ng-checked="selected.indexOf(channel[3]) > -1" ng-click="toggleSelection(channel[3])" value="channel[3]">CHANNEL D</md-checkbox>
<md-checkbox ng-model="channel[4]" class="margin-left-1 md-primary md-hue-2" ng-checked="selected.indexOf(channel[4]) > -1" ng-click="toggleSelection(channel[4])" value="channel[4]">CHANNEL E</md-checkbox>
我正在尝试将值放在数组中。 我的指令代码是: -
scope.channels = ['CHANNEL A','CHANNEL B','CHANNEL C','CHANNEL D','CHANNEL E'];
scope.selected = [];
scope.toggleSelection = function toggleSelection(channel) {
console.log(channel);
var idx = scope.selected.indexOf(channel);
console.log(idx);
if (idx > -1) {
scope.selected.splice(idx, 1);
}
else {
scope.selected.push(channel);
}
};
我知道通过使用ng-repeat它会更好地工作但是通过使用我有一些其他css问题难以纠正。我只希望这种方法起作用。任何人都可以告诉我如何在不使用ng-repeat的情况下使其工作。
答案 0 :(得分:2)
我还建议让ngRepeat工作,但要回答问题......
不要同时使用ngModel和ngChecked。
试试这个:
<label>CHANNELS</label>
<md-checkbox ng-model="selected[0]" class="md-primary md-hue-2" ng-true-value="channel[0]" ng-false-value="null">CHANNEL A</md-checkbox>
<md-checkbox ng-model="selected[1]" class="md-primary md-hue-2" ng-true-value="channel[1]" ng-false-value="null">CHANNEL B</md-checkbox>
<md-checkbox ng-model="selected[2]" class="md-primary md-hue-2" ng-true-value="channel[2]" ng-false-value="null">CHANNEL C</md-checkbox>
<md-checkbox ng-model="selected[3]" class="md-primary md-hue-2" ng-true-value="channel[3]" ng-false-value="null">CHANNEL D</md-checkbox>
<md-checkbox ng-model="selected[4]" class="md-primary md-hue-2" ng-true-value="channel[4]" ng-false-value="null">CHANNEL E</md-checkbox>
如果选中此框,则会将selected
数组的值设置为channel
数组的对应值。注意:您无法使用selected.length
来确定是否检查了任何内容,因为selected
数组将始终包含4个成员,其中一些成员可能为空。