Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
160 views
in Technique[技术] by (71.8m points)

javascript - How do I return data from a $http.get() inside a factory in angularjs

I'm having a lot of trouble with this and I can't seem to find anything here on SO or Google that helps me spot what I'm doing wrong

<!DOCTYPE html>
<html data-ng-app="testApp">
   <head>
      <title></title>
   </head>
   <body>
      <div data-ng-controller="myController">
         {{test}}<br/>
         {{test2}}<br/>
         {{test3}}
         <ul>
            <li data-ng-repeat="member in members">{{ member.firstname}}</li>
         </ul>
      </div>
      <script type="text/javascript" src="angular.min.js"></script>
      <script type="text/javascript">
         angular.module('testApp', ['memberFactory']);

         angular.module('testApp',[])
         .factory('memberFactory', function($http){

            var obj = {};
            obj.data = "abcd";
            obj.getResponse = function(){
                var temp = {};
                $http.get('hello.php').success(function(data){
                        alert(data);
                        temp =data;

                });

                return "some return value";
            }

            return obj
         });

         function myController($scope, memberFactory){ 
            $scope.test= "testString";
            $scope.test2= memberFactory.data;
            $scope.test3= memberFactory.getResponse();

         }
      </script>
   </body>
</html>

the return "some return value"; works but when I try to return temp, its null. I have tried various ways to get this to work but I just can't seem to set the temp value inside the $http.get() function

It is probably something simple (or a silly mistake/misguided approach on my part). Any advice would be greatly appreciated

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use defer:

obj.getResponse = function(){                 
    var temp = {};
    var defer = $q.defer();
    $http.get('hello.php').success(function(data){
            alert(data);
            temp =data;
            defer.resolve(data);

    });
    return defer.promise;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...