1

I try to use $scope inside a factory to stock a value but i can't.

I try also to push the value into an array, it doesn't work.

I just want to copy a callback value into a variable to return it from a factory.

This is a sample :

var cpy = {};
$http.get('/api/things/')
.success(function (data){
          cpy = data;
         })
        .error(function (err){

        });

console.log(cpy);

Thanks for your help.

4
  • you must use promsie. docs.angularjs.org/api/ng/service/$q Commented May 20, 2015 at 9:16
  • @user3227295 $http already return a promise. Commented May 20, 2015 at 9:18
  • the console.log function fired before callback function Commented May 20, 2015 at 9:20
  • @user3227295 You don't need to explicitly use promise cause $http.get() already return one. This is just the workflow that wasn't good. Check my answer if you want some detail. Commented May 20, 2015 at 9:24

2 Answers 2

0

That was almost what you need.

You factory should look like :

var getCopy = function(){
    return $http.get('/api/things/');
}

And in your controller you get it like this :

myfactory.getCopy().success(function(data){
   $scope.myscopedvar = data;
});

If you want some binding in your scope it'll always be done in the controller. If it's an asynchronous call, it's the responsibility of your controller to know what to do when the $http promise resolve.

Hope it helped, if you want more explanation feel free to ask.

Sign up to request clarification or add additional context in comments.

Comments

0

Thanks to Maxim, Okazari and user3227295.

my factory look like this :

angular.module('feedbackApp').factory('Data', function ($http, $q, Auth) {
    $http.get('/api/things/')
    .success(function (data){
              cpy = data;
             })
            .error(function (err){

            });
                return {first : true}; 
          });

I just want to check if cpy was not empty to return false and return true for empty variable.

Sorry to asked the question without much precisions.

Thank you.

2 Comments

Did you try my solution ? You should do this in your controller in the .success() method
it doesn't work, I need a factory because I have bootstrap modal to displayu a welcome message just one time, when you close it, I insert into database, then every login you will not see the welcome message.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.