我正在尝试选中所有复选框,单击选择/取消选中页面上的所有其他复选框。
我的HTML是这样的:
<table class="table table-striped">
<thead>
<tr class="table-header">
<th ng-if="!newTestSessionCtrl.formData.battery.id"><input type="checkbox" ng-click="newTestSessionCtrl.selectAllTests()" ng-model=".allSelected" /></th>
<th>Test</th>
<th>Available Time</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in newTestSessionCtrl.formData.battery.testDefinitions">
<td ng-if="!newTestSessionCtrl.formData.battery.id"><input type="checkbox" ng-model="row.selected" ng-change="newTestSessionCtrl.optionToggled(); newTestSessionCtrl.validate()" /></td>
<td>{{row.name}}</td>
<td>{{(row.duration / 60) | number:0}} minutes</td>
</tr>
</tbody>
</table>
这是来自我的控制器的代码:
class NewTestSessionController {
constructor($scope, $state, resources, NewTestSessionService, formats, AuthenticationService, toastr, momentTimezone, _) {
this.allSelected = false;
}
selectAllTests() {
let isSelected = true;
if (this.allSelected) {
isSelected = false;
}
angular.forEach(this.formData.battery.testDefinitions, function(v) {
v.checked = !isSelected;
this.allSelected = !isSelected;
});
}
optionToggled() {
this.allSelected = true;
angular.forEach(this.formData.battery.testDefinitions, function(v) {
if(!v.checked) {
this.allSelected = false;
}
});
}
}
问题在于allSelected变量,当我点击select all复选框时,我收到有关未定义的错误:
我是否试图以某种错误的方式访问它?当我使用调试器时,这个变量不是未定义的,所以我不确定我是否在寻找合适的位置? 这个问题应该很容易实现,但我仍然不擅长Angular。有人看到了这个问题吗?
答案 0 :(得分:2)
使用Arrow Function
代替function()
声明。
<强>代码强>
selectAllTests() {
let isSelected = true;
if (this.allSelected) {
isSelected = false;
}
//arrow function to make current this available inside function
angular.forEach(this.formData.battery.testDefinitions, (v) => {
v.checked = !isSelected;
this.allSelected = !isSelected;
});
}
optionToggled() {
this.allSelected = true;
//arrow function to make current this available inside function
angular.forEach(this.formData.battery.testDefinitions, (v) => {
if(!v.checked) {
this.allSelected = false;
}
});
答案 1 :(得分:0)
scope
问题this
。
this
范围在回调函数中不可用。
将this
分配给另一个变量,并在callbacks
用此代码替换控制器。
class NewTestSessionController {
constructor($scope, $state, resources, NewTestSessionService, formats, AuthenticationService, toastr, momentTimezone, _) {
this.allSelected = false;
}
selectAllTests() {
let _this = this;
let isSelected = true;
if (this.allSelected) {
isSelected = false;
}
angular.forEach(this.formData.battery.testDefinitions, function(v) {
v.checked = !isSelected;
_this.allSelected = !isSelected;
});
}
optionToggled() {
let _this = this;
this.allSelected = true;
angular.forEach(this.formData.battery.testDefinitions, function(v) {
if(!v.checked) {
_this.allSelected = false;
}
});
}
}