我只是尝试在Angular JS中创建一个服务,它成功调用函数$ http.get并返回值。但是,该值不会插入范围变量中。 问题:出了什么问题?
angular.module('starter.controllers', [])
.factory('UserService', function($http) {
var data;
return{
getData: function($http) {
return $http.get('http://www.website.com/call12').
success(function(response) {
/// console.log(JSON.stringify(response));
userData=response.data;
return userData;
}).error(function(data, status, headers, config) {
// log error
});
}
}
})
.controller('AppCtrl', function($scope, $ionicModal, $interval,$http,$rootScope,UserService) {
$scope.formData={};
$scope.userData={};
$scope.myCtrl= function(UserService,$http,$rootScope) {
UserService.getData($http).then(function(data,$rootScope) {
$scope.userData = data;
$scope.fullName = data.name;
$scope.balance = data.balance;
}}
$scope.formData.playerName= $scope.userData.name; // $scope.userData is undefined
$scope.myCtrl(UserService,$http);
})
模板
<form ng-submit="submit_editpw()" ng-controller="AppCtrl">
<pre>userData : {{userData}}</pre> //retuns data
<pre>name: {{fullName}}</pre> //returns empty
</form>
答案 0 :(得分:2)
您没有使用异步getData
方法。由于这是promise object,您应该使用其then
方法:
UserService.getData().then(function(data) {
$scope.userData = data;
});
还要确保getData
返回一个承诺:
getData: function () {
return $http.get('http://m.sepakbola.cc/index.php/id/user/call12').success(function (response) {
userData = response.data;
return userData;
}).error(function (data, status, headers, config) {
// log error
});
}
答案 1 :(得分:0)
在服务中将promise作为响应返回,并在控制器中使用promise success回调将值赋给userData
angular.module('starter.controllers', [])
.factory('UserService', function($http) {
var data;
return{
getData: function() {
return $http.get('http://www.website123.com/call12');
}
}
})
.controller('AppCtrl', function($scope, $ionicModal, interval,$http,$rootScope,UserService) {
$scope.myCtrl= function(UserService,$http) {
$scope.userData={};
UserService.getData().success(function(reponse) {
$scope.userData=response.data;
});
}