angularjs 中的 foreach 循环 [英] foreach loop in angularjs

查看:24
本文介绍了angularjs 中的 foreach 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 AngularJS 中浏览了 forEach loop.有几点我不明白.

  1. 迭代器函数有什么用?没有它有什么办法吗?
  2. 如下所示的键和值的意义是什么?

angular.forEach($scope.data, function(value, key){});

PS:我尝试在没有参数的情况下运行此函数,但它不起作用.

这是我的json:

<预><代码>[{"姓名": "托马斯",密码":托马斯国王"},{"姓名": "琳达",密码":lindatheQueen"}]

我的 JavaScript 文件:

var app = angular.module('testModule', []);app.controller('testController', function($scope, $http){$http.get('Data/info.json').then(功能(数据){$scope.data = 数据;});angular.forEach($scope.data, function(value, key){if(value.Password == "thomasTheKing")console.log("用户名是托马斯");});});

另一个问题:为什么上面的函数没有进入if条件并在控制台打印username is thomas"?

解决方案

问题 1 &2

所以基本上,第一个参数是要迭代的对象.它可以是一个数组或一个对象.如果是这样的对象:

var values = {name: 'misko', 性别: 'male'};

Angular 会一个一个取每一个值,第一个是名字,第二个是性别.

如果您要迭代的对象是一个数组(也可能),如下所示:

[{ "Name" : "Thomas", "Password" : "thomasTheKing" },{姓名":琳达",密码":lindatheQueen"}]

Angular.forEach 将从第一个对象开始一个一个,然后是第二个对象.

对于这个对象中的每一个,它都会一个一个地获取它们并为每个值执行特定的代码.此代码称为迭代器函数.如果您使用的是集合数组,forEach 是智能的并且行为会有所不同.这是一些例子:

var obj = {name: 'misko', 性别: 'male'};var log = [];angular.forEach(obj, function(value, key) {console.log(key + ': ' + value);});//它将像这样记录两次迭代//名称:misko//性别:男

所以键是键的字符串值,值是...值.您可以使用密钥访问您的值,如下所示:obj['name'] = 'John'

如果这次你显示一个数组,像这样:

var values = [{ "Name" : "Thomas", "Password" : "thomasTheKing" },{姓名":琳达",密码":lindatheQueen"}];angular.forEach(values, function(value, key){console.log(key + ': ' + value);});//它将像这样记录两次迭代//0: [对象对象]//1: [对象对象]

那么 value 是您的对象(集合),key 是您的数组的索引,因为:

[{ "Name" : "Thomas", "Password" : "thomasTheKing" },{姓名":琳达",密码":lindatheQueen"}]//等于{0:{姓名":托马斯",密码":托马斯国王"},1:{姓名":琳达",密码":lindatheQueen"}}

我希望它能回答你的问题.这是一个 JSFiddle,可以运行一些代码并进行测试:http://jsfiddle.net/ygahqdge/

调试代码

问题似乎来自 $http.get() 是一个异步请求.

您向您的儿子发送查询,然后当您的浏览器结束下载它时,它执行成功.但是在发送您的请求后,您使用 angular.forEach 执行循环,而无需等待 JSON 的回答.

您需要在成功函数中包含循环

var app = angular.module('testModule', []).controller('testController', ['$scope', '$http', function($scope, $http){$http.get('Data/info.json').then(function(data){$scope.data = 数据;angular.forEach($scope.data, function(value, key){if(value.Password == "thomasTheKing")console.log("用户名是托马斯");});});});

这应该可行.

更深入

<块引用>

$http API 基于 deferred/promise$q 公开的 API服务.而对于简单的使用模式,这并不重要,对于高级用法 熟悉这些 API 很重要以及他们提供的保证.

你可以看看deferred/promise APIs,它是Angular 的一个重要概念,使异步操作变得流畅.

I was going through the forEach loop in AngularJS. There are few points that I did not understood about it.

  1. What is the use of the iterator function? Is there any way to go without it?
  2. What is the significance of the key and value as shown below?

angular.forEach($scope.data, function(value, key){});

PS: I tried to run this function without the arguments and it did not work.

Here's my json:

[
   {
     "Name": "Thomas",
     "Password": "thomasTheKing"
   },
   {
     "Name": "Linda",
     "Password": "lindatheQueen"
   }
]

My JavaScript file:

var app = angular.module('testModule', []);

app.controller('testController', function($scope, $http){
   $http.get('Data/info.json').then(
      function(data){
         $scope.data = data;
      }
   );

   angular.forEach($scope.data, function(value, key){
      if(value.Password == "thomasTheKing")
         console.log("username is thomas");
   });
});

Another question: Why the function above does not enter on if condition and print "username is thomas" in the console?

解决方案

Questions 1 & 2

So basically, first parameter is the object to iterate on. It can be an array or an object. If it is an object like this :

var values = {name: 'misko', gender: 'male'};

Angular will take each value one by one the first one is name, the second is gender.

If your object to iterate on is an array (also possible), like this :

[{ "Name" : "Thomas", "Password" : "thomasTheKing" },
 { "Name" : "Linda", "Password" : "lindatheQueen" }]

Angular.forEach will take one by one starting by the first object, then the second object.

For each of this object, it will so take them one by one and execute a specific code for each value. This code is called the iterator function. forEach is smart and behave differently if you are using an array of a collection. Here is some exemple :

var obj = {name: 'misko', gender: 'male'};
var log = [];
angular.forEach(obj, function(value, key) {
  console.log(key + ': ' + value);
});
// it will log two iteration like this
// name: misko
// gender: male

So key is the string value of your key and value is ... the value. You can use the key to access your value like this : obj['name'] = 'John'

If this time you display an array, like this :

var values = [{ "Name" : "Thomas", "Password" : "thomasTheKing" },
           { "Name" : "Linda", "Password" : "lindatheQueen" }];
angular.forEach(values, function(value, key){
     console.log(key + ': ' + value);
});
// it will log two iteration like this
// 0: [object Object]
// 1: [object Object]

So then value is your object (collection), and key is the index of your array since :

[{ "Name" : "Thomas", "Password" : "thomasTheKing" },
 { "Name" : "Linda", "Password" : "lindatheQueen" }]
// is equal to
{0: { "Name" : "Thomas", "Password" : "thomasTheKing" },
 1: { "Name" : "Linda", "Password" : "lindatheQueen" }}

I hope it answer your question. Here is a JSFiddle to run some code and test if you want : http://jsfiddle.net/ygahqdge/

Debugging your code

The problem seems to come from the fact $http.get() is an asynchronous request.

You send a query on your son, THEN when you browser end downloading it it execute success. BUT just after sending your request your perform a loop using angular.forEach without waiting the answer of your JSON.

You need to include the loop in the success function

var app = angular.module('testModule', [])
    .controller('testController', ['$scope', '$http', function($scope, $http){
    $http.get('Data/info.json').then(function(data){
         $scope.data = data;

         angular.forEach($scope.data, function(value, key){
         if(value.Password == "thomasTheKing")
           console.log("username is thomas");
         });
    });

});

This should work.

Going more deeply

The $http API is based on the deferred/promise APIs exposed by the $q service. While for simple usage patterns this doesn't matter much, for advanced usage it is important to familiarize yourself with these APIs and the guarantees they provide.

You can give a look at deferred/promise APIs, it is an important concept of Angular to make smooth asynchronous actions.

这篇关于angularjs 中的 foreach 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆