0

I have a function that I am calling to splice through some list of items and will make a network call to send in the newly ordered list to the DB.

My problem is that I want to only allow for users to re-order once the network call is finished. I’m trying to do that with a promise method but it seems to not be working well for me.

I am setting a variable completed to false and changing it to true once the network call has been finished…my approach might be wrong so if someone’s done something like this before, some advice would be appreciated.

Here is what I have so far…

$scope.moveDown = function(array, element) {
        var index = array.indexOf(element);
        var completed = false;

        if(index === -1){
          return false;
        }

        if(array[index + 1] && completed === true){
          // rearranging elements
          array.splice(index, 2, array[index + 1], array[index]);
          // network call
          teacherList.saveOrder(id, teachers).then(function(resolve) {
            resolve(completed === true);
          });
        }else {
          // Do nothing
          return 0;
        }
      };
jeremy
  • 433
  • 1
  • 8
  • 30

1 Answers1

0

in angular you must use promises.

First; add the promise dependency in your controller : $q

Then; update your network call to be a promise :

       var myService = function() {

                var d = $q.defer();

                var configQuery = {
                    'url': myUri,
                    'method': "GET"
                };
                $http(configQuery).then(function(res) {


                    d.resolve(res);

                }, function(err) {
                    d.reject(err);
                })

                return d.promise;


            }

Note that $http is already a promise; I splitted it to be more clear on my explanation.

Finally; call your code when promise is done :

//call your http promise
myService().then(function(){
    //success add your function call
    $scope. moveDown()
}, function(err){
//error callback
});

EDIT---

If you want you can add your call to your $http sucess response :

var myFunction = function(){
    $http(configQuery).then(function(res) {
        $scope. moveDown()

    }, function(err) {

    });
 }
aorfevre
  • 5,034
  • 3
  • 21
  • 51
  • hmm so in my case...i should put the re-ordering function $scope.movdDown() inside the network call? – jeremy Jun 14 '17 at 14:21
  • YEs; when the promise of your network call is finished. Updated my response with that example. – aorfevre Jun 14 '17 at 14:22