angularJS 使用服务变量

angularJS using service variable

我需要在控制器中调用服务变量。 我试图在服务函数外调用 $scope.userData1.data.name,它是未定义的。 如果我将 {{userData1}} 放入模板 Messages Ctrl 中,它会显示包括名称在内的所有数据数组。

我需要使用 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">&nbsp;</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,因为此时服务器尚未 return 回复 (http.get)。
在调用下一行 (var name= $scope.userData1.data.name;) 之前,您必须确保此函数 $scope.myCtrl2(UserService,$http) 收到异步应答。

最好的解决方案是像这样使用 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);
  });
})