2016-10-11 5 views
0

함수의 ng-repeat에서 항목을 업데이트하려면 어떻게해야합니까? 다음 코드가 있습니다. 내 HTML 파일에서 반복 : 나는 각도 모달 서비스 (http://dwmkerr.github.io/angular-modal-service/)를 사용하고각도 업데이트 기능의 항목

<div ng-repeat='item in collection'> 
    <div class="product-item"> 
     <img src="{{item.image}}"/> 
     {{item.name}} 
     {{item.price}} 
     <a ng-href='' ng-click='showPricePopup(item)'>Update price</a> 
    </div> 
</div> 

및 컨트롤러에 다음 함수 생성 :

$scope.showPricePopup = function(item){ 
     ModalService.showModal({ 
      templateUrl: "/winkelier/modal/price", 
      controller: "priceCtrl", 
      inputs: { 
       item: item 
      } 
     }).then(function(modal) { 
      modal.close.then(function(result) { 
       console.log("result", result.item); 
       $scope.updateItem(result.item); 
       item = result.item; 
      }) 
     }) 
    } 

priceCtrl에서 나는 $ 범위, 항목을 삽입하고 항목을 닫고 범위에 복사하십시오.

angular.module('myApp').controller('priceCtrl', ["$scope", "$http", 'item', 'close', function($scope, $http, item, close) { 

    $scope.modalitem = angular.copy(item); 
    $scope.savedmodalItem = angular.copy($scope.modalitem); 

내가이 컨트롤러도 close()cancel() 기능을 생성 :

$scope.close = function(){ 
    close({ 
     item: $scope.modalitem 
    }, 500); 
} 

$scope.cancel = function(){ 
    $scope.modalitem = angular.copy($scope.savedmodalItem); 
    close({ 
     item: $scope.modalitem 
    }, 500);  
} 

문제는 다음과 같다 : 일부 숙박 시설의 항목에서를 업데이트하고 cancel() 버튼을 클릭하면 아무 일도 발생하지 않습니다. 괜찮아. 그러나 일부 속성을 변경하고 close()을 클릭하면 항목이 $scope.updateItem()을 통해 업데이트되지만 ng-repeat의 항목은 업데이트되지 않습니다.

어떻게 해결할 수 있습니까? 당신이 할 수있는 상기와 가까운 기능의

답변

1

은 원본을 수정하지 않을 때문에, 당신은 새로운 항목을 배열의 인덱스에있는 항목을 대체해야합니다

$scope.showPricePopup = function(item){ 
    var itemIndex = $scope.collection.indexOf(item); // get the index 
    ModalService.showModal({ 
     templateUrl: "/winkelier/modal/price", 
     controller: "priceCtrl", 
     inputs: { 
      item: item 
     } 
    }).then(function(modal) { 
     modal.close.then(function(result) { 
      console.log("result", result.item); 
      $scope.updateItem(result.item); 
      $scope.collection[itemIndex] = result.item; // replace the item at that index 
     }) 
    }) 
} 

배열이 메모리 포인터의 무리는 것을 기억하십시오. item은 메모리의 해당 항목을 가리키는 로컬 변수이지만 item = result.item;을 입력하면 로컬item 변수가 배열의 인덱스가 아니라 새 주소를 가리 키도록 설정합니다.

1

:

var close = function() { 
    // do what you do before 
    $scope.$apply(); 
} 

이.