Reputation: 547
In a CRUD scenario it’s very common to load a list of records, then reload it after adding a new record. You’ll end up with something like this:
angular.module('myApp')
.controller('UsersController', function($scope,UserService) {
UserService.all().then(function(users) {
$scope.users = users;
};
$scope.addUser = function(userData) {
UserService.add(userData).then(function() {
UserService.all().then(function(users) {
$scope.users = users;
};
};
};
});
As you can see I have UserService.all() called twice even in addUser scope which I think this is a wrong aproach.
How would I eliminate this kind of duplicate code..
I have heard using state Resolve would eliminate such duplicate code, what is your opinion?
Upvotes: 0
Views: 114
Reputation: 17492
Well this is really not specific to angular, you would approach this as you would with any kind of code. You could wrap the duplicate code in another method and call that instead:
$scope.reloadUsers=function(){
UserService.all().then(function(users) {
$scope.users = users;
};
};
And then call $scope.reloadUsers()
instead of calling UserService.all()
.
Upvotes: 1