I have an angular view which displays a list of items and for each there are two buttons that set each campaign on pause/start. I know it's a very basic problem with angular $resource, but I can't update the item on success $start (in the success callback I can't access anything related to the item).
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;
}]);
and in views I have:
<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>
This is a closure/scope related question, not Angular itself. Inside the success handler, this
is not the scope anymore, so there is no way to access this.campaign
. You actually can solve this problem in a bunch of ways.
The simples, I belive, is to receive the campaign
as parameter and just reference it from there:
You already have this in your HTML:
ng-click="startCampaign(campaign)"
So receive and use it:
$scope.startCampaign = function (campaign) {
var c = new Campaign(campaign);
c.$start(function success(response) {
campaign.status = 1;
},
...
};