programing

어떻게 내 angular.js ng-model에 json을 로드하지?

lastcode 2023. 3. 28. 21:50
반응형

어떻게 내 angular.js ng-model에 json을 로드하지?

나는 매우 당연한 질문을 가지고 있지만, 어디에서도 답을 찾을 수 없었다.

서버에서 클라이언트로 JSON 데이터를 로드하려고 합니다.현재 JQuery를 사용하여 AJAX 콜(아래 코드)로 로드하고 있습니다.

<script type="text/javascript">
var global = new Array();
$.ajax({
    url: "/json",
    success: function(reports){
        global = reports;
        return global;
        }
    });
</script>

이것은 html 파일에 있습니다.아직까지는 가능하지만, 문제는 Angular JS를 사용하고 싶다는 것입니다.Angular CAN이 변수를 사용하는 동안 모든 것을 변수에 로드할 수 없으므로 각 루프에 대해 를 사용할 수 있습니다.이는 보통 .js 파일에 있는 "$Scope"와 관련이 있는 것으로 보입니다.

문제는 다른 페이지에서 .js 파일로 코드를 로드할 수 없다는 것입니다.Angular의 모든 예에서는 다음과 같은 내용만 보여 줍니다.

function TodoCtrl($scope) {
  $scope.todos = [
    {text:'learn angular', done:true},
    {text:'build an angular app', done:false}];

따라서, 이것은, I A) 이 모든 것을 손으로 타이핑 하고 싶은 경우, 및 B) 모든 데이터가 어떤 것인지 미리 알고 있는 경우, 도움이 됩니다.

미리 알 수 없고(데이터는 동적입니다), 타이핑하고 싶지 않습니다.

그래서 $Resource를 사용하여 AJAX 콜을 Angular로 변경하려고 해도 작동하지 않는 것 같습니다.잘 모르겠지만 JSON 데이터에 대한 비교적 간단한 GET 요청입니다.

tl:dr 외부 데이터를 각도 모델에 로드하기 위해 AJAX 호출이 작동하도록 할 수 없습니다.

크리스가 언급했듯이$resource서버와 대화하는 서비스입니다만, Angular와의 여정을 시작하고 있는 것 같은 느낌이 듭니다.-저는 지난주에 거기에 있었습니다.- 그래서 저는 이 서비스를 사용하여 직접 실험을 시작할 것을 권장합니다.$http서비스.이 경우는, 다음의 콜을 실시할 수 있습니다.get방법.

다음과 같은 JSON이 있는 경우

[{ "text":"learn angular", "done":true },
 { "text":"build an angular app", "done":false},
 { "text":"something", "done":false },
 { "text":"another todo", "done":true }]

이렇게 장전할 수 있습니다.

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

App.controller('TodoCtrl', function($scope, $http) {
  $http.get('todos.json')
       .then(function(res){
          $scope.todos = res.data;                
        });
});

getmethod는 첫 번째 인수가 성공 콜백이고 두 번째 인수가 오류 콜백인 약속 개체를 반환합니다.

추가할 때$httpAngular 함수의 파라미터로서 마법에 의한 동작과 주입을 실시합니다.$http리소스를 컨트롤러에 넣습니다.

여기 몇 가지 예를 들겠습니다.

다음은 JSON 데이터를 Angular 모델에 로드하는 간단한 예입니다.

Microsoft Northwind SQL Server 데이터베이스의 온라인 복사본에서 고객 상세 목록을 반환하는 JSON 'GET' 웹 서비스가 있습니다.

http://www.iNorthwind.com/Service1.svc/getAllCustomers

다음과 같은 JSON 데이터가 반환됩니다.

{ 
    "GetAllCustomersResult" : 
        [
            {
              "CompanyName": "Alfreds Futterkiste",
              "CustomerID": "ALFKI"
            },
            {
              "CompanyName": "Ana Trujillo Emparedados y helados",
              "CustomerID": "ANATR"
            },
            {
              "CompanyName": "Antonio Moreno Taquería",
              "CustomerID": "ANTON"
            }
        ]
    }

..드롭다운 리스트를 이 데이터로 채우고 싶습니다.이렇게 하려면...

앵글 스크린샷

각 항목의 텍스트는 "CompanyName" 필드에서, ID는 "Customer"에서 가져옵니다.[ID] 필드

내가 어떻게 하겠어?

Angular 컨트롤러는 다음과 같습니다.

function MikesAngularController($scope, $http) {

    $scope.listOfCustomers = null;

    $http.get('http://www.iNorthwind.com/Service1.svc/getAllCustomers')
         .success(function (data) {
             $scope.listOfCustomers = data.GetAllCustomersResult;
         })
         .error(function (data, status, headers, config) {
             //  Do some error handling here
         });
}

...는 "listOfCustomers" 변수를 이 JSON 데이터 세트로 채웁니다.

그리고 HTML 페이지에서 다음을 사용합니다.

<div ng-controller='MikesAngularController'>
    <span>Please select a customer:</span>
    <select ng-model="selectedCustomer" ng-options="customer.CustomerID as customer.CompanyName for customer in listOfCustomers" style="width:350px;"></select>
</div>

그리고 이것이 마지막입니다.이제 웹 페이지에서 바로 사용할 수 있는 JSON 데이터 목록을 볼 수 있습니다.

이 문제의 열쇠는 "ng-options" 태그에 있습니다.

customer.CustomerID as customer.CompanyName for customer in listOfCustomers

이해가 잘 안 되는 구문이군요!

사용자가 이 목록에서 항목을 선택하면 "$scope"가 표시됩니다.selected Customer" 변수가 ID(고객)로 설정됩니다.고객 레코드의 ID 필드).

이 예의 완전한 스크립트는 다음 URL에서 확인할 수 있습니다.

각도가 있는 JSON 데이터

마이크

나는 다음 코드를 사용했는데, 인터넷 어딘가에서 소스를 기억하지 못한다.

    var allText;
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function () {
        if (rawFile.readyState === 4) {
            if (rawFile.status === 200 || rawFile.status == 0) {
                allText = rawFile.responseText;
            }
        }
    }
    rawFile.send(null);
    return JSON.parse(allText);

언급URL : https://stackoverflow.com/questions/13020821/how-to-load-json-into-my-angular-js-ng-model

반응형