Search code examples
javascriptangularjscontrollerangularjs-serviceangularjs-controller

How can I call the function in controller from service


I would like to ask if is posible call function getItems(); in ItemController controller(It loads list of data) from fileUpload service(after upload image) - exaple bellow.

After upload I want to refresh list of items but I dont know how I should write the callback...

Thank you for help.

    app.controller('ItemController', ['$scope', '$http', 'fileUpload', function($scope, $http, fileUpload){
    getItems();
  function getItems(){  
  $http.post("../db/getItems.php").success(function(data){
        $scope.items = data;
       });
  };

...
...
...
...


app.service('fileUpload', ['$http', function ($http) {

        this.uploadFileToUrl = function(file, object, extId){
           var fd = new FormData();
           fd.append('file', file);
              $http.post("../db/upload.php?object="+object+"&extId="+extId, fd, {
                  transformRequest: angular.identity,
                  headers: {'Content-Type': undefined}
               })

               .success(function(data){
                  alert(JSON.stringify(data));
                  ItemController.getItems(); // <= Here....after upload I would like to call function getItems()
                  
               })
    
               .error(function(){
               });
        }
     }]);


Solution

  • What you should do is, do return a $http promise from a service method & then on that promise success call your controller method. Executing controller function into service isn't good practice to do, though you can achieve it by passing function as callback.

    this.uploadFileToUrl = function(file, object, extId){
       var fd = new FormData();
       fd.append('file', file);
       return $http.post("../db/upload.php?object="+object+"&extId="+extId, fd, {
           transformRequest: angular.identity,
           headers: {'Content-Type': undefined}
       });
    };
    

    And then inside a controller you could call service method & then execute controller function on resolve of that promise

    fileUpload.uploadFileToUrl().then(function(data){
       getItems(); //controller function.
    })