【问题标题】:How to iterate through angular $scope variables with a loop如何使用循环遍历角度 $scope 变量
【发布时间】:2013-06-23 23:44:27
【问题描述】:

我想用这样的 for 循环遍历 $scope 变量。 在这个例子中,$scope 对象包括一个对象 accounts 包括 5 个对象,其名称是从 1 到 5 的数字。每个对象都有一个名称。

for(var i = 1; i < 5; i++){
   $('#name').val($scope.accounts.i.name);
}

问题: $scope.accounts.iundefined 因为 i 不算作 $scope 内的变量 变量。 它算作字母 i,所以我看不到使用 for 循环遍历范围的机会。 当我在 $scope 变量周围使用“”时,它只会显示为纯 html,并且不会解释 angular。

【问题讨论】:

  • 那么 account 是一个包含五个键值对的 5 个对象的数组?
  • accounts 是一个包含 5 个对象和几个键值对的数组。但当然,每个账户都有相同数量的货币对。 ;)

标签: angularjs scope angularjs-scope


【解决方案1】:

上面的角度方法是

 $scope.accounts=[{name:"123"},{name:"124"},{name:"125"}]

            angular.forEach($scope.accounts,function(value,index){
                alert(value.name);
            })

【讨论】:

    【解决方案2】:

    如果accounts是一个数组,可以使用数组索引器:

    for(var i = 1; i < 5; i++){
       $('#name').val($scope.accounts[i].name);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-12
      • 2016-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-07
      • 1970-01-01
      • 2015-06-09
      相关资源
      最近更新 更多