2014-01-22 1 views
0

AngularJs 자습서를 작성 중이며 JSON에 액세스하고 싶습니다. 튜토리얼에서 []를 사용하여 JSON에 액세스하는 이유를 이해할 수 없습니다.Angular에서 JSON에 특별한 방식으로 액세스해야하는 이유는 무엇입니까?

HTML :

<html ng-app> 
<head> 
    <title>Demo</title> 
    <script type="text/javascript" src="js/lib/angular.min.js"></script> 
    <script type="text/javascript" src="js/controllers/app.js"></script> 
</head> 
<body> 
<div ng-controller="AppCtrl"> 
    <h1>AngulAir</h1> 
    <ul> 
     <li ng-repeat="airport in airports"> 
      <a href="" ng-click="setAirport(airport.code)"> 
       {{airport.code}} - {{airport.city}} 
      </a> 
     </li> 
    </ul> 
    <p ng-show="currentAirport">Current Airport : {{currentAirport.name}}</p> 
</div> 

하고 "태그"에 사용자가 클릭 그것이 setAirport 기능에 airport.code를 넣고 를 currentAirport.name을 다시 얻을 때 여기에 코드입니다 이것은 JS 코드입니다 :

function AppCtrl ($scope) { 
    $scope.airports = { 
    "PDX": { 
     "code": "PDX", 
     "name": "Portland International Airport", 
     "city": "Portland", 
     "destinations": [ 
     "LAX", 
     "SFO" 
     ] 
    }, 
    "STL": { 
     "code": "STL", 
     "name": "Lambert-St. Louis International Airport", 
     "city": "St. Louis", 
     "destinations": [ 
     "LAX", 
     "MKE" 
     ] 
    } 
    }; 
    $scope.currentAirport = null; 

    $scope.setAirport = function (code){ 
    $scope.currentAirport = $scope.airports[code]; 
    }; 
} 

마지막 문장에서 볼 수 있습니다. ---> $ scope.currentAirport = $ scope.airports [code]; []를 사용하여 JSON에 액세스합니다. 나는 그것이 왜 이렇게 사용되는지 이해하지 못합니다.

HTML :

<html> 
<head> 

    <title>hello world</title> 
</head> 
<body> 

</body> 

<script type="text/javascript" src=jsfile.js></script> 

<script type="text/javascript"> 

alert(airports[code]); 

</script> 

JS 파일 :

airports = { 
    "PDX": { 
     "code": "PDX", 
     "name": "Portland International Airport", 
     "city": "Portland", 
     "destinations": [ 
     "LAX", 
     "SFO" 
     ] 
    }, 
    "STL": { 
     "code": "STL", 
     "name": "Lambert-St. Louis International Airport", 
     "city": "St. Louis", 
     "destinations": [ 
     "LAX", 
     "MKE" 
     ] 
    } 
}; 

나는 내 브라우저에이 얻을 "나는 다른 상황에서 실험을 시도하고 다르게 작동하는 것 같다, 여기에 내 실험입니다 ReferenceError : 변수를 찾을 수 없습니다 : 코드 "왜? 이 문장의 JSON 액세스 방법 -----> $ scope.currentAirport = $ scope.airports [code]; 이 문장과 동등하지 않습니다 -----> alert (airports [code]); ?????

두 번째 경우 []을 사용할 수없는 이유는 무엇입니까?

$scope.setAirport = function (code){ 
    $scope.currentAirport = $scope.airports[code]; 
}; 

code

가 함수에 전달되고, 그들은 공항 오브젝트의 공항 코드를 참조 사용 : 사람이 첫 번째 예에서 나에게

+0

문제는 공항 [코드]을 사용할 수 없다는 것이 아니라 "코드"라는 변수를 정의하지 않은 것이 문제입니다. "var code = 'PDX'; 줄을 추가하십시오. "alert (airports [code]);"앞에 줄에 따옴표 (따옴표 제외)를 입력하십시오. 다시 시도하십시오. –

+0

이 질문은 Angular와 관련이 없으며 JSON과도 관련이없는 것으로 보입니다. 변수를 정의하지 않았을 때 어떻게 정의 될 것으로 기대합니까? – Pavlo

답변

3

을 알려주세요 알고있다. 당신의 예에서

:

alert(airports[code]); 

code는 정의되지 않습니다.

코드를 정의하거나 수동으로 공항 코드를 전달해야합니다.

+0

noobie에 대해 이해할 수 있으며, 실수를 저질 렀어, 고마워요 ^^ – user3156452

관련 문제