angularJS使用服务变量
问题描述:
我需要调用控制器中的服务变量。 我试图在服务函数外面调用$scope.userData1.data.name
,它是未定义的。 如果我将{{userData1}}
放在模板Messages Ctrl中,它会显示包含名称的所有数据数组。angularJS使用服务变量
我需要使用user_name变量加载i-帧。
angular.module('starter.controllers', [])
.factory('UserService', function($http) {
var data;
return{
getData: function($http) {
return $http.get("http://www.website.com/index.php/id/user/call12").
success(function(response) {
/// console.log(JSON.stringify(response));
userData=response.data;
return userData;
}).error(function(data, status, headers, config) {
// log error
});
}
}
})
.controller('MessagesCtrl',function ($scope, Messages,$http,$ionicPopup,$timeout,$window,UserService,Outbox,$sce) {
$scope.userData1 = {}; // updated
$scope.myCtrl2= function(UserService,$http) {
UserService.getData($http).then(function(data) {
$scope.userData1 = data;
console.log($scope.userData1.data.name); // USERNAME exist
var name= $scope.userData1.data.name;
});
}
$scope.myCtrl2(UserService,$http);
var name= $scope.userData1.data.name; //undefined
$scope.formData4.upload_url = $sce.trustAsResourceUrl("http://www.website.com/index.php/id/user/view_form/"+ name);
})
模板:
<form ng-controller="MessagesCtrl" ng-disabled="isRequesting">
<span class="item item-input" >
<span class="input-label"> </span>
<iframe id="iframe-123" src="{{formData4.upload_url}}" style="border: 0px none; height: 80px; margin: auto; width: 100%; overflow: hidden;" frameborder=0></iframe></span>
</form>
答
你,因为在这一点上得到了undefined
,答案(http.get)尚未从服务器返回。
您必须确保此函数$scope.myCtrl2(UserService,$http)
在您可以调用下一行(var name = $ scope.userData1.data.name;)之前收到异步答案。
最好的解决方案是使用promise
- $q
服务是这样的:
.controller('MessagesCtrl',function ($scope, Messages,$http,$ionicPopup,$timeout,$window,UserService,Outbox,$sce,$q) {
$scope.userData1 = {}; // updated
$scope.myCtrl2= function(UserService, $http)
{
var deferred = $q.defer();
UserService.getData($http).then(function(data)
{
$scope.userData1 = data;
console.log($scope.userData1.data.name); // USERNAME exist
var name= $scope.userData1.data.name;
deferred.resolve();
});
return deferred.promise;
}
$scope.myCtrl2(UserService,$http).then(function(){
var name= $scope.userData1.data.name; //Now you got the answer!!!
$scope.formData4.upload_url = $sce.trustAsResourceUrl("http://www.website.com/index.php/id/user/view_form/"+ name);
});
})
的
+0
非常感谢。我最近学习AJS。我终于得到了答案。 – xyonme 2015-01-21 09:06:26
可能重复[如何返回从Ajax响应调用?](http://*.com/questions/14220321/how-to-return-the-an-ajax-call) – 2015-01-21 05:57:11
@AlexisKing嗨Alexis。回应已经以良好的形式回复。但是响应的范围在称为Service的函数之外是不可用的。 – xyonme 2015-01-21 06:09:20
问题是因为当使用构造'MessagesCtrl'时,'$ scope.userData1.data.name'已经在'$ http'的'callback'被触发之前被评估 - >因为你没有初始化'$ scope.userData1'。而另一件关于你的代码的东西,你不需要因'javascript closure'将'UserService'和$'http'注入到'$ scope.myCtrl2'中。看看这个小提琴,我已经改变你的$ http到$超时,但它应该以同样的方式工作。希望能帮助到你。 http://jsfiddle.net/themyth92/w0st1y7e/ – themyth92 2015-01-21 07:56:12