0

我有一個角度視圖,顯示項目列表,每個項目有兩個按鈕用於設置每個廣告系列的暫停/啓動。我知道這是角度$資源的一個非常基本的問題,但我無法更新成功$ start(在成功回調中,我無法訪問與該項目相關的任何東西)的項目。

function CampaignsListCtrl($scope, Campaign, $resource) { 
    $scope.campaigns = Campaign.query(); 

    $scope.startCampaign = function() { 
     var c = new Campaign(this.campaign); 
     c.status = 1; 
     c.$start(function success(response) { 
       //here I'd like to update the value but can't access the item. 
       //for example this.campaign.status = 1 doesn't work 
       //how can I access the ng-repeat item to update it on success $start? 
       //the response represents the updated Object 

       console.log (response); 

     }, function error (response) { 
      console.log (response) 
     }); 
    } 

    $scope.pauseCampaign = function() { 
     var c = new Campaign(this.campaign); 
     c.status = 0; 
     c.$pause(function success(response) { 
       console.log (response); 

     }, function error (response) { 
      console.log (response) 
     }); 
    } 

} 
//// and Campaign is defined as factory 
mongoAPI. 
factory('Campaign', ['$resource', '$http', function($resource, $http) { 
     var actions = { 
      'start': {method:'POST'},       
      'pause': {method:'POST'}     
     } 
     var res = $resource('/api/campaign.js',{}, actions) 
     return res; 
}]); 

和意見,我有:

<div ng-repeat="campaign in campaigns"> 
    <button type="button" ng-show="campaign.status==0" ng-click="startCampaign(campaign)" class="btn"><i class="icon-play"></i></button> 
    <button type="button" ng-show="campaign.status==1" ng-click="pauseCampaign(campaign)" class="btn"><i class="icon-pause"></i></button> 
</div> 

回答

1

這是一個封閉/範圍相關的問題,沒有棱角本身。在成功處理程序中,this不再是範圍,因此無法訪問this.campaign。你實際上可以用很多方法解決這個問題。

的simples,我相信,是接收campaign作爲參數,只是從那裏引用它:

你已經有這個在你的HTML:

ng-click="startCampaign(campaign)" 

因此接收和使用它:

$scope.startCampaign = function (campaign) { 
    var c = new Campaign(campaign); 
    c.$start(function success(response) { 
     campaign.status = 1; 
    }, 
    ... 
}; 
相關問題