我正在尝试从对象中索引为 0 的对象中提取 ID。然后我需要将此 key 转换为字符串,以便能够将其传递到 api 端点。
我的 Controller 事件:
$scope.attach = function () {
var rules_id = $scope.rules.selected;
if (rules_id) {
var l = rules_id.length;
for (var i = 0, j = l; i < j;)
{
var key_value = rules_id[i];
}
}
console.log($scope.rules);
console.log(key_value);
console.log($scope.rules.selected);
console.log($scope.asset.id);
};
目前,我只是尝试在控制台中定义每个变量,唯一返回未定义的是循环变量“key_value”。
我已经根据循环的许多示例和标准设置对此进行了检查,但这是行不通的。
$scope.rules.selected 是一个复选框结果,其键由规则 ID 表示。见下文:
<form name="rules" method="post">
<table class="table table-striped table-hover" ng-model="associated_rules">
<thead>
<th>Rule ID:</th>
<th>Rule Types:</th>
<th>Description:</th>
<th>Start Time:</th>
<th>End Time:</th>
<th>Apply Rule to Vehicle:</th>
</thead>
<tr ng-repeat="associated_rule in associated_rules">
<td>@{{ associated_rule.id }}</td>
<td>@{{ associated_rule.resource_ids.accounts }}</td>
<td>@{{ associated_rule.description }}</td>
<td>@{{ associated_rule.start_time }}</td>
<td>@{{ associated_rule.end_time }}</td>
<td><input type="checkbox" ng-model="rules.selected[associated_rule.id]"aria-label="associated_rule.id" ng-true-value="true"ng-false-value="false" value="rules.selected"></td></tr>
</table>
<button class="btn btn-primary" ng-click="attach()"><i class="fa fa-paperclip"></i> Attach</button>
</form>
最佳答案
您的 for 循环是错误的,您还试图控制台记录一个在 for 循环内声明的变量,它永远是未定义的! 这是正确的 for 循环示例:
for (i = 0; i < rules_id.length; i++) {
console.log(rules_id[i]);
}
请阅读如何for loop作品
但真正的问题在于你的 Angular 代码
关于javascript - 我如何让这个循环工作?它返回未定义的 angularjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36481392/