javascript - 我如何让这个循环工作?它返回未定义的 angularjs

标签 javascript angularjs loops

我正在尝试从对象中索引为 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/

相关文章:

loops - 使用 Haskell 读取 n 行输入

javascript - 如何在网站上保留用户的事件日志?

javascript - 更改字母算法,在 JSBIN 中有效,但在 Coderbyte 中无效,寻求澄清

javascript - 如何在按钮组中输出变量以影响 Angular.js 和 Html 中的下拉结果

javascript - 如何将 Controller 中的指令绑定(bind)到 HTML 中?

python - 如何根据元素在它们来自的列表中是否彼此相邻来拆分列表?

javascript - AngularJS + Bootstrap flexBox 不兼容?

javascript - 异步等待 + Gulp - GulpUglifyError : unable to minify JavaScript?

javascript - Angular.js 点击进入项目详细信息页面

无法在 For 循环内执行 Switch 语句超过 10 次 - C