【发布时间】:2015-01-21 03:49:43
【问题描述】:
我需要在控制器中调用服务变量。
我试图在服务函数之外调用$scope.userData1.data.name,它是未定义的。
如果我将 {{userData1}} 放在模板 Messages Ctrl 中,它会显示所有数据数组,包括名称。
我需要使用 user_name 变量加载 i-frame。
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>
【问题讨论】:
-
@AlexisKing 嗨,亚历克西斯。已以良好的形式返回响应。但是响应的范围在调用Service的函数之外是不可用的。
-
问题是因为当使用构造
MessagesCtrl时,$scope.userData1.data.name在$http的callback被触发之前已经被评估->得到undefined因为你没有初始化@ 987654332@ 还没有。关于您的代码的另一件事是,由于javascript closure,您不需要将UserService和$http注入您的$scope.myCtrl2。看看这个小提琴,我已经将你的 $http 更改为 $timeout 但它应该以相同的方式工作。希望能帮助到你。 jsfiddle.net/themyth92/w0st1y7e -
嗨 @themyth92 嗨,感谢您查看我的代码。我在函数外使用服务变量时遇到问题。在函数 myCtrl2() 中,我可以跟踪用户名,但使用
$scope.userData1.data.name我没有定义。你了解我的情况吗? -
在你的 jsfiddle 上,如果我把
var name = $scope.userData1.data.name;// undefined放在 $scope.myCtrl2(); 下面的行上在我的情况下它将返回未定义
标签: javascript angularjs iframe