【问题标题】:How do I get this loop to work? It's returning undefined angualrjs如何让这个循环工作?它返回未定义的 angularjs
【发布时间】:2016-04-07 15:56:23
【问题描述】:

我正在尝试从对象索引中为 0 的对象中提取 ID。然后我需要将此密钥转换为字符串,以便能够将其传递到 api 端点。

我的控制器事件:

        $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>

【问题讨论】:

  • 你能粘贴console.log($scope.rules);结果?
  • 你应该使用var rules_id = Object.keys($scope.rules.selected); 吗?为什么for (var i = 0, j = l; i &lt; j;)?
  • ng-model 不应用于
  • 您是 JavaScript 新手吗?只是想知道,因为您的 JS 代码中有很多错误。如果你是新手,我不建议以 Angular 为起点来学习。

标签: javascript angularjs loops


【解决方案1】:

你的 for 循环是错误的,你也试图控制台记录一个在 for 循环中声明的变量,它总是未定义的! 这是正确的 for 循环示例:

for (i = 0; i < rules_id.length; i++) {
    console.log(rules_id[i]); 
}

请阅读for loop 的工作原理

但这里真正的问题在于您的 Angular 代码

【讨论】:

  • 感谢@Akis_Tfs,您的建议没有奏效。
  • Kd {$error: Object, $$success: Object, $pending: undefined, $name: "rules", $dirty: true...} $$parentForm : Object $$renameControl : (a ,b) $$success : 对象 $addControl : (a) $commitViewValue : () $dirty : true $error : 对象 $invalid : false $name : "rules" $pending : 未定义 $pristine : false $removeControl : (a ) $rollbackViewValue : () $setDirty : () $setPristine : () $setSubmitted : () $setUntouched : () $setValidity : (a,e,f) $submitted : true $valid : true selected : Object 原型 : 对象
  • 您的问题是关于 for 循环不起作用,您将不得不提出一个与您的角度代码有关的新问题
  • 循环语法是正确的,我已经检查过了,我认为循环的模型正在被访问,这可能意味着我需要提出另一个问题,谢谢你的帮助。
【解决方案2】:

如果您以更具声明性的方式重新思考,您想要的内容也许可以存档:

// creates the module
angular.module("samplemodule",[])

// apppend the controller to the module
angular.module("samplemodule").controller("SampleCtl",function(){

  this.values = [// sample data
    {a:"XXX",b:0,c:new Date(),d:true },
    {a:"XXY",b:1,c:new Date(),d:false},
    {a:"XYX",b:2,c:new Date(),d:false},
    {a:"XYY",b:3,c:new Date(),d:true },
    {a:"YXX",b:4,c:new Date(),d:false},
    {a:"YXY",b:5,c:new Date(),d:false}
  ]
  
  this.attach = function attach(){
    var selectedones = this.values.filter(function(e){ 
      return e.d // just the selected ones
    }).map(function(e){
      return e.b // just the ids or anything you want
    }).join(",")
    alert(selectedones)
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="samplemodule" ng-controller="SampleCtl as ctl">
  <table>
    <thead>
      <tr>
        <th>A</th>
        <th>B</th>
        <th>C</th>
        <th></th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="vl in ctl.values">
        <td>{{vl.a}}</td>
        <td>{{vl.b}}</td>
        <td>{{vl.c}}</td>
        <td><input type="checkbox" ng-model="vl.d"/></td>
      </tr>
    </tbody>
  </table>
  <button ng-click="ctl.attach()">The selected ones</button>
</div>

【讨论】:

  • 您好,感谢您的建议。我已经尝试过了,但我认为问题是我试图从中提取的模型。这是复选框输入的输出日志: Object {db77370c-fbfe-11e5-8468-ed8c21fd14a1: true, c9f2c76c-fbfe-11e5-8fe5-70c120bc96b2: true} 关键是我想要掌握的,然后将其记录为单数字符串,并且每次我希望引用该键时,它都会以未定义的形式返回 - 即使它在从我的 $scope 变量调用时显示在视图中。完全糊涂了。
  • 哦,我明白了@Ben,问题是您的模型根本不是 json 对象列表,而是该格式的字符串。您可以在将每个日志条目放入模型之前对其进行修改吗?我会在几分钟内调整示例,以更好地解释我要问的问题。
【解决方案3】:

在这种方法中,我们采用一些格式良好的输入并进行一些转换,以便更好地利用它

    // creates the module
    angular.module("samplemodule",[])

    // apppend the controller to the module
    angular.module("samplemodule").controller("SampleCtl",function(){

      // log data from somewhere
      this.originalData = [
        "{db77370c-fbfe-11e5-8468-ed8c21fd14a1: true, c9f2c76c-fbfe-11e5-8fe5-70c120bc96b5: true}",
        "{db77370c-fbfe-11e5-8468-ed8c21fd14a2: false, c9f2c76c-fbfe-11e5-8fe5-70c120bc96b6: true}",
        "{db77370c-fbfe-11e5-8468-ed8c21fd14a3: true, c9f2c76c-fbfe-11e5-8fe5-70c120bc96b7: true}",
        "{db77370c-fbfe-11e5-8468-ed8c21fd14a4: true, c9f2c76c-fbfe-11e5-8fe5-70c120bc96b8: false}",
        
      ]
      
      this.values = this.originalData.map(function(e){
        e = e.replace(/{/g,"{\"").replace(/:/g,"\":").replace(/, /g,", \"")
        e = JSON.parse(e)
        var kv = []
        for(var attr in e)
          kv.push({key:attr,value:e[attr]})
        return kv
      })
      
      this.attach = function attach(){
        var selectedones = [].concat.apply([],this.values).filter(function(e){
          return e.value
        })
        alert(selectedones)
      }
    })
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="samplemodule" ng-controller="SampleCtl as ctl">
      <table>
        <tbody>
          <tr ng-repeat="vl in ctl.values">
            <td ng-repeat="kv in vl">
              {{kv.key}}
              <input type="checkbox" ng-model="kv.value"/>
            </td>
          </tr>
        </tbody>
      </table>
      <button ng-click="ctl.attach()">The selected ones</button>
    </div>

【讨论】:

    猜你喜欢
    • 2016-09-27
    • 2022-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-08
    相关资源
    最近更新 更多