我正在尝试将 BootstrapSwitch 库实现到我的 Angular 4 项目中。我创建了以下指令:
import {Directive, ElementRef, Input, AfterViewInit} from '@angular/core';
@Directive({ selector: '[switch]' })
export class SwitchDirective implements AfterViewInit {
@Input() onText: string;
@Input() offText: string;
@Input() labelText: string;
directive: any;
constructor(el: ElementRef) {
this.directive = $(el.nativeElement);
$.fn.bootstrapSwitch.defaults.onColor = 'success';
}
ngAfterViewInit() {
var options = {
onText: this.onText,
offText: this.offText,
labelText: this.labelText,
};
this.directive.bootstrapSwitch(options);
this.directive.on('switch-change', function () {
this.directive.bootstrapSwitch('toggleRadioState');
});
this.directive.on('switch-change', function () {
this.directive.bootstrapSwitch('toggleRadioStateAllowUncheck');
});
this.directive.on('switch-change', function () {
this.directive.bootstrapSwitch('toggleRadioStateAllowUncheck', false);
});
}
}
我的输入结构是:
<input type="checkbox" class="make-switch" onText="Y" offText="N" labelText="Switch 1" switch #switch1>
<input type="checkbox" class="make-switch" onText="Y" offText="N" labelText="Switch 2" switch #switch2>
我可以将它与表单提交一起使用,如下所示:
<button (click)="submit(switch1.checked, switch2.checked)">Submit</button>
但是,当我尝试与 ngModel 绑定时,它不起作用。
<input type="checkbox" class="make-switch" onText="Y" offText="N" labelText="Switch 1" switch [(ngModel)]="selectedItem.switch1" name="switch1" [checked]="selectedItem.switch1== 1">
<input type="checkbox" class="make-switch" onText="Y" offText="N" labelText="Switch 2" switch [(ngModel)]="selectedItem.switch2" name="switch2" [checked]="selectedItem.switch2 == 1">
缺少的是我猜想在 angularjs 中有如下类似的方法:
element.on('switchChange.bootstrapSwitch', function(event, state) {
if (ngModel) {
scope.$apply(function() {
ngModel.$setViewValue(state);
});
}
});
任何帮助表示赞赏。