2014-12-15 9 views
3

저는 AngularJS를 처음 사용하면서 문제가 있습니다.

내가 통해 검색 송장의 JSON 배열을 가지고 $ HTTP GET 여기를 통해 반복되는 요청 :

<a ng-repeat="invoice in invoices" href="#" class="list-group-item"> 
    {{ invoice[data]["TxnDate"][0] }} - 
    {{ invoice[data]["DocNumber"][0] }} - 
    ${{ invoice[data]["TotalAmt"][0] }} - 
    {{ getCustomer(invoice[data]["Id"][0]) }} 

    <i class="fa fa-chevron-right pull-right"></i> 
    <i class="pull-right">Edit</i> 
    </a> 

문제는 송장의 배열을 제외하고 고객에 대한 정보를 저장하지 않는다는 것입니다 고객의 참조 번호

그래서 참조 번호로 고객의 이름을 API에 쿼리하는 getCustomer이라는 함수를 만들었습니다.

error: [$rootscope:infdig] 10 $digest() iterations reached. aborting! watchers fired in the last 5 iterations: [] 

후, 나는이 작업을 수행 할 수있는보다 효율적인 방법을 알아낼 것이다하지만이 오류의 원인이 무엇인지 궁금 :

$scope.getCustomer = function(id) { 

    var customer_id = id.match(/\d+/)[0]; 

    $http.post('/customers', customer_id).success(function(response) { 
     console.log(response); 
    }); 

}; 

문제이 오류를 수신하고 있습니까?

몇 가지 조사를 한 후에 목록 항목 중 하나의 데이터가 변경되면 AngularJS는 모든 목록 항목을 검사해야한다는 사실과 관련이 있다고 생각합니다. 아직도, 나는 매우 혼란 스럽다. 이 일을 올바르게 수행하는 방법은 무엇입니까?

+0

은에서 온다? 그 약간의 코드를 보여줄 수 있습니까? – maurycy

+0

@RaphaelRafatpanah 당신은 귀하의 데이터 구조 (즉, 송장)에 대한 통찰력을 게시해야합니다. 그것은 무엇처럼 보입니다. "데이터"인덱서 란 무엇입니까? 인보이스 구조 등을 위해 2 레벨 중첩 배열을 사용하고 있습니까? – cleftheris

+0

방금 ​​귀하의 업데이트를 읽었습니다. 이것을 피하고 아이템을 컬렉션에 추가하거나 제거 할 때 ng-repeat를 새로 고치려면 다음과 같이 간단히 "track by"표기법을 사용할 수 있습니다 :'ng-repeat = "인보이스 추적에서 $ index" '. [ng-repeat] (https://docs.angularjs.org/api/ng/directive/ngRepeat)에 대한 angularjs 설명서를 참조하십시오. 중첩 된 항목의 필드가 변경 될 때마다 변경되는 계산 된 $ 해시를 기반으로 기본 구현이 새로 고쳐집니다. – cleftheris

답변

6

문제는 바인딩 내부에서 함수를 사용하는 것과 관련이 있습니다 (보간 {{}}). 그 특성으로 인해, angularjs는 변경 사항에 대한 $ scope (뷰 모델)을 지속적으로 관찰합니다. 따라서 조심하지 않으면 항상 객체의 새로운/다른 인스턴스를 반환하는 함수에 바인딩 할 수 있습니다. 이렇게하면 각도가 오류로 식별되고 스택 오버 플로우가 발생하지 않도록 바인딩을 비활성화하는 무한 루프가 트리거됩니다. 반환 된 고객을 로컬 변수에 저장하도록 함수를 변경했다고 말하면 문제를 피할 수 있습니다.

여기에 전체 스 니펫이 있습니다. 송장을하지

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

 
app.controller('MainCtrl', function($scope, $http, $q) { 
 
    $scope.invoices = [ 
 
    { Id: "1", TxnDate: new Date(2014, 6, 26), DocNumber: "I0", TotalAmt: 200.34 }, 
 
    { Id: "2", TxnDate: new Date(2014, 8, 2), DocNumber: "I000021", TotalAmt: 530.34 }, 
 
    { Id: "3", TxnDate: new Date(2014, 11, 15), DocNumber: "I000023", TotalAmt: 123 }, 
 
    { Id: "4", TxnDate: new Date(2014, 12, 11), DocNumber: "I000027", TotalAmt: 5000 }, 
 
    ]; 
 
    
 
    var testUrl = 'http://echo.jsontest.com/company/AKME/firstName/John/lastName/Doe'; 
 
    var _customerCache = {}; 
 
    $scope.customerCache = _customerCache; 
 
    $scope.getCustomer = function(id) { 
 
    var deferred = $q.defer(); // defer 
 
    if (_customerCache[id]) 
 
     return deferred.resolve(_customerCache[id]); 
 
    
 
    var customer_id = id.match(/\d+/)[0]; 
 

 
    $http.get(testUrl + customer_id + '/id/'+ customer_id).success(function(response) { 
 
     console.log(response); 
 
     _customerCache[id] = response; 
 
     deferred.resolve(response); 
 
    }); 
 
    return deferred.promise; 
 
}; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="main" ng-controller="MainCtrl"> 
 
    <ul> 
 
    <li ng-repeat="invoice in invoices" ng-init="getCustomer(invoice.Id)"> 
 
    <a href="#" class="list-group-item"> 
 
     {{ invoice.TxnDate | date }} - 
 
     {{ invoice.DocNumber }} - 
 
     {{ invoice.TotalAmt | currency }} 
 
     {{ customerCache[invoice.Id].firstName }} {{ customerCache[invoice.Id].lastName }} 
 
    </a> 
 
    </li> 
 
    </ul> 
 
    <span>customers via http</span> 
 
    <ul> 
 
    <li ng-repeat="cust in customerCache"> 
 
     {{cust}} 
 
    </li> 
 
    </ul> 
 
<div>

+0

이 작동하지만 겨우. 오류는 계속 표시되지만 브라우저가 중단되지 않고 올바른 값이보기로 리턴됩니다. {{}} 밖에서이 함수를 호출 할 수있는 방법이 있습니까? –

+1

invgices에서 ng-init user2700840

+0

@RaphaelRafatpanah 전 runnable 스 니펫으로 답변을 업데이트했습니다 . 희망이 도움이됩니다. – cleftheris

관련 문제