gpt4 book ai didi

javascript - 无法在 AngularJs 中设置未定义的属性

转载 作者:行者123 更新时间:2023-12-02 13:46:51 25 4
gpt4 key购买 nike

我正在尝试创建一个全选复选框,单击该复选框将选择/取消选择页面上的所有其他复选框。

我的 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>

这是我的 Controller 的代码:

    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 变量上,当我单击全选复选框时,出现未定义的错误:

enter image description here

我是否试图以错误的方式访问它?当我使用调试器时,这个变量不是未定义的,所以我不确定我是否在正确的位置查找?这个问题应该很容易实现,但我仍然不擅长 Angular。有人发现问题了吗?

最佳答案

使用箭头函数代替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;
}
});

关于javascript - 无法在 AngularJs 中设置未定义的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41332609/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com