search

Home  >  Q&A  >  body text

angular.js - How does the controller get the value returned by the factory in angularjs?

var app = angular.module("MyApp", []);

app.factory("myFactory", function ($http) {

    return {
        
        getDatas: function () {

            var args = {};
            var url = "test.req";

            $http({
                method: 'POST',
                data: args,
                url: url
            }).success(function (response, status, headers, config) {

                return response;


            }).error(function (response, status, headers, config) {

                alert(status + response);

            });

        }

    };

});

app.controller("myCtrl", function ($scope, myFactory) {

    $scope.names = {};
    $scope.title = myFactory.msg;

    alert(myFactory.getDatas());
    $scope.names = myFactory.getDatas();

});

In the above code, alert(myFactory.getDatas());
if the value of factory cannot be obtained, undefined will be displayed.
Browser debug display:
angular1.5.3.min.js:6Uncaught Error: [$injector:modulerr]

The factory can obtain data from the backend, but the controller does not know how to obtain the factory data from each other...

世界只因有你世界只因有你2782 days ago638

reply all(1)I'll reply

  • 黄舟

    黄舟2017-05-15 17:02:43

    I just started watching angular recently...


    You see, the getDatas method is actually an asynchronous function execution body. Once getDatas is executed, $http will asynchronously request the back-end data. However, after getDatas is executed, it returns, and alert cannot get the value.

    app.factory("myFactory", function ($http) {
        return {
            getDatas:function(){
                 return $http.get('data/data.json');//return 一个promise
            }
        }
    
    });
    
    app.controller("myCtrl", function ($scope, myFactory) {
    
        $scope.names = {};
        $scope.title = myFactory.msg;
    
        //alert(myFactory.getDatas());
        myFactory.getDatas().success(function (response, status, headers, config) {
                            //要用到返回数据就在这里用了
                            console.log(response);
                            
    
    
                        }).error(function (response, status, headers, config) {
    
                            alert(status + response);
    
                        });
       //下面这句看起来像是要获取数据,挪到上面的success去  $scope.xxx=
        $scope.names = myFactory.getDatas();
    
    });

    reply
    0
  • Cancelreply