S
S
Sergey Nikolaev2015-05-28 17:14:53
JavaScript
Sergey Nikolaev, 2015-05-28 17:14:53

How to properly update the $scope of an Angular controller?

Good afternoon friends!
Let's say I have a function in my controller that is responsible for passing some array received from the server to $scope

function MyCtrl($scope, req, calc){
$scope.update = function() {
        req.post('c=users&a=getAll', {}, function (res) {
                res = calc.calc(res[i]);
                $scope.items = res;
            }
        });
}
$scope.update();
}

I also have another controller in which I send data from the form to the server
function Add($scope, req){
$scope.save = function(){
        req.post('c=users&a=add', $scope.mydata, function(res){
             //в этом callback необходимо что то вроде MyCtrl.update();
        });
    }
}

After adding, the first controller needs to send a request to the server again and write the updated data to $scope.
What is the best way to implement something like this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
_
_ _, 2015-05-28
@AMar4enko

You need to write a service that encapsulates all external interactions.

User
   .getAll
   .add (после успешного выполнения запроса вызывает .onUserAdded)
   .onUserAdded

function MyCtrl($scope, req, calc, User){
  $scope.update = function() {
        User.getAll(function (res) {
                res = calc.calc(res[i]);
                $scope.items = res;
            }
        });
  }
  User.onUserAdded($scope.update);
  $scope.update();
}

function Add($scope, req, User){
  $scope.save = function(){
    User.add($scope.mydata);    
  }
}

Thus, when a user is added, the onUserAdded handler will be called, to which the MyCtrl controller will be subscribed, which will cause the list to be updated.
You just have to implement all this.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question