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();
});