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...
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.