I'm just starting to use AngularJS.
I have a simple CRUD app which communicates to REST api. I have two controllers which control my Projects data and Tasks data respectfully. On the backend Tasks are liked by foreign key to the parent Project. So when I delete a Project the associated Tasks are also deleted (this is the functionality I want right now).
So everything works except that when I delete a Project I want to reload the Tasks list. Basically after ConcernService.del('projects/', item) is called I want the Tasks list to be refreshed from the API. I know this should be handled via the ConcernsService, but I'm not sure of the best way.
// --- CONCERNS FACTORY --- //
concernsApp.factory('ConcernService', function ($http, $q) {
var api_url = "/path/to/api/";
var ConcernService = {
list: function (items_url) {
var defer = $q.defer();
$http({method: 'GET', url: api_url + items_url}).
success(function (data, status, headers, config) {
defer.resolve(data);
}).error(function (data, status, headers, config) {
defer.reject(status);
});
return defer.promise;
},
del: function(item_url, obj) {
return $http.delete(api_url + item_url + obj.id + '/');
},
};
return ConcernService;
});
// --- PROJECTS CONTROLLER --- //
concernsApp.controller('ProjectsCtrl', function ($scope, $http, ConcernService) {
// get all projects
$scope.projects = ConcernService.list('projects/');
// assign the delete method to the scope
$scope.deleteItem = function(item) {
ConcernService.del('projects/', item).then(function(){
// reload projects
$scope.projects = ConcernService.list('projects/');
});
};
});
// --- TASKS CONTROLLER --- //
concernsApp.controller('TasksCtrl', function ($scope, $http, ConcernService) {
// get all tasks
$scope.tasks = ConcernService.list('tasks/');
// assign the delete method to the scope
$scope.deleteItem = function(item) {
ConcernService.del('tasks/', item).then(function(){
// reload projects
$scope.tasks = ConcernService.list('tasks/');
});
};
});