I have a bunch of 'campaigns' in my database:
{"name" : "Apple", "status" : "active"}
{"name" : "Orange", "status" : "paused"}
I've displayed them in Angular with:
<span ng-switch on="campaign.status">
<a ng-switch-when="active" ng-click='setStatus($index, "paused")'>Pause</a>
<a ng-switch-when="paused" ng-click='setStatus($index,"active")'>Activate</a>
</span>
Then in my controller I update the status on the server's database using an API (which returns JSON of the updated entry.
$scope.setStatus = function(index, newstatus) {
var item = $scope.campaigns[index];
var url = 'api.mysite.com/' + newstatus + '/' + item._id.$oid;
if (! $scope.isComplete(item) )
{
$http({method: 'GET', url: url}).
success(function(data, status, headers, config) {
$scope.campaigns[index] = data;
}). error(function(data, status, headers, config) {
console.log('Error communicating with the server.');
});
}
}
Where the variable campaigns is an array of all the campaigns retrieved from the server when the controller is initialized with:
$scope.connection = $resource('api.mysite/getallcampaigns');
$scope.campaigns = $scope.connection.query();
This seems really messy already and I'm pretty sure I'm using AngularJS incorrectly :( The main thing is that I'm passing into the controller the index of the element I'm modifying, which break if I re-order the array. How can I get Angular to wire this up nicely for me? What's the minimal and correct way to do this?
Pass campaign into setStatus() instead of an index. Modify the campaign properties in the success callback:
<a ng-switch-when="active" ng-click='setStatus(campaign, "paused")'>Pause</a>
.
$scope.setStatus = function (campaign, newstatus) {
...
success(function(data, status, headers, config) {
campaign.status = data.status;
Don't reassign the entire array in the success callback -- that will likely break databinding in your view.
I.e., I don't think this will work: campaign = data
You can probably define one $resource object that can handle both getting the initial array of data and modifying individual array items. See the "Credit card resource" example on the $resource API page. Note how each item of array cards (which is assigned the result of query()) can also be $save()d.