program tip

angularjs의 foreach 루프

radiobox 2020. 8. 7. 08:16
반응형

angularjs의 foreach 루프


나는 통해 가고 있었다 forEach loop에서 AngularJS. 내가 이해하지 못한 점이 몇 가지 있습니다.

  1. 반복기 기능의 사용은 무엇입니까? 그것없이 갈 방법이 있습니까?
  2. 아래와 같이 키와 값의 의미는 무엇입니까?

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

추신 : 이 함수를 인수없이 실행하려고했지만 작동하지 않았습니다.

여기 내 json:

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

JavaScript파일 :

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");
   });
});

또 다른 질문 : 왜 위의 함수가 if condition에 들어 가지 않고 콘솔에 "username is thomas"를 출력합니까?


질문 1 및 2

따라서 기본적으로 첫 번째 매개 변수는 반복 할 객체입니다. 배열 또는 객체 일 수 있습니다. 다음과 같은 객체 인 경우 :

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

Angular는 첫 번째는 이름이고 두 번째는 성별입니다.

반복 할 객체가 배열이면 다음과 같이 가능합니다.

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

Angular.forEach는 첫 번째 개체에서 시작하여 두 번째 개체를 하나씩 가져옵니다.

이 객체 각각에 대해 하나씩 가져와 각 값에 대해 특정 코드를 실행합니다. 이 코드를 반복기 함수 라고 합니다 . forEach는 스마트하며 컬렉션 배열을 사용하는 경우 다르게 작동합니다. 다음은 몇 가지 예입니다.

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

따라서 key는 키의 문자열 값이고 값은 ... 값입니다. 키를 사용하여 다음과 같이 값에 액세스 할 수 있습니다.obj['name'] = 'John'

이번에 다음과 같이 배열을 표시하면 :

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]

따라서 value는 객체 (컬렉션)이고 key는 배열의 인덱스입니다.

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

귀하의 질문에 대한 답변이 되었기를 바랍니다. 다음은 일부 코드를 실행하고 원하는 경우 테스트하는 JSFiddle입니다. http://jsfiddle.net/ygahqdge/

코드 디버깅

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.


you have to use nested angular.forEach loops for JSON as shown below:

 var values = [
        {
            "name":"Thomas",
            "password":"thomas"
        },
        { 
            "name":"linda",
            "password":"linda"
        }];

    angular.forEach(values,function(value,key){
        angular.forEach(value,function(v1,k1){//this is nested angular.forEach loop
            console.log(k1+":"+v1);
        });
    });

The angular.forEach() will iterate through your json object.

First iteration,

key = 0, value = { "name" : "Thomas", "password" : "thomasTheKing"}

Second iteration,

key = 1, value = { "name" : "Linda", "password" : "lindatheQueen" }

To get the value of your name, you can use value.name or value["name"]. Same with your password, you use value.password or value["password"].

The code below will give you what you want:

   angular.forEach(json, function (value, key)
         {
                //console.log(key);
                //console.log(value);
                if (value.password == "thomasTheKing") {
                    console.log("username is thomas");
                }
         });

Change the line into this

 angular.forEach(values, function(value, key){
   console.log(key + ': ' + value);
 });

 angular.forEach(values, function(value, key){
   console.log(key + ': ' + value.Name);
 });

In Angular 7 the for loop is like below

var values = [
        {
            "name":"Thomas",
            "password":"thomas"
        },
        { 
            "name":"linda",
            "password":"linda"
        }];

for (let item of values)
{
}

참고URL : https://stackoverflow.com/questions/29953198/foreach-loop-in-angularjs

반응형