2016-10-11 49 views
0

如何更新函数中的ng-repeat项目? 我有以下代码。 在我的HTML文件中的重复:角度 - 功能更新项目

<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> 

我采用了棱角分明模式服务(http://dwmkerr.github.io/angular-modal-service/),并创造了控制器的以下功能:

$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(); 
} 

这一点。