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();
});
以上代码中alert(myFactory.getDatas());
获取不到factory的值的,显示undefined。
浏览器debug显示:
angular1.5.3.min.js:6Uncaught Error: [$injector:modulerr]
factory能够从后端获取到数据,就是controller这头不知道怎么互获取factory的数据.....
黄舟2017-05-15 17:02:43
最近才开始看angular……
你看getDatas方法里面实际上是一个异步函数执行体,getDatas一执行,然后$http就去异步请求后端数据了,但getDatas执行完了,就return了 ,alert拿不到值咯。
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();
});