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; 
    }, 
    ... 
}; 
相关问题