javascript - Angular $scope 在 Angular Controller 中的函数之外没有值

标签 javascript angularjs

简介: 我在 $http 方法中遇到返回值问题,我了解如何在 $http.post 和 $http.get 方法中使用 $http,我无法在调用我的工厂的函数之外返回值。

我需要在 Controller 功能之外使用 $scope.historias 值。

我的 Angular 工厂: 第一工厂:

mediperbaricaApp.factory('listarTratamientos',['$http','$location','$q', 
                                                function($http, $location, $q){
    var urlBase = host + 'index.php/';
    var service = {};
    console.log('DEBUG = entramos');

    return {
        response : function(response){
            return $http({
                url : (urlBase + 'tratamientos/getTratamientos'),
                method : 'GET' 
            })
        }
    }

}]);

第二工厂:

mediperbaricaApp.factory('services', [ '$http' ,'$location', function(
                                                    $http, $location){
  var urlBase = host + 'index.php/';
  var service = {};
  //listado de historias para el autocoplete del form
  service.getHistorias = function(callback){
    console.log('[DEBUG] FAC Listar Historias');
    $http.get(urlBase + 'historias/getHistoria').
    success(function(response){
        return callback(response);
    }).
    error(function(response){
        alert('Lo sentimos!, No se puede recuperar los datos, ' +
                                                      ' intente mas tarde :(');
    })
  };

  return service;
}]);

我的 Angular Controller Controller ,使用最后两个工厂,我得到相同的结果

mediperbaricaApp.controller('editController',function($scope,listarTratamientos,
                                         $location,$routeParams, services){
    console.log('[DEBUG] CTRL editar tratamientos');
    //use first factory
    $scope.datos = {};
    services.getHistorias(function(response){
        $scope.datos = response.data; // output array with data :)
    })
    //the data no exist in this place.
    console.dir($scope.datos); //$scope.datos lost data :(

    //use second factory
    $scope.midata = {};
    listarTratamientos.response().success(function(data){
        $scope.midata = data;
        console.dir($scope.midata);  // output array with data :)
    });
    //data not exist in this place i dont understand
    console.dir($scope.midata); //$scope.datos lost data :(

谢谢你的帮助! 注意。爱德华多

最佳答案

因此,在这部分中,您有一个回调函数,并且您尝试访问其下面的代码中的值:

services.getHistorias(function(response){
        $scope.datos = response.data; // output array with data :)
    })
    //the data no exist in this place.
    console.dir($scope.datos); //$scope.datos lost data output undefined variable :(

问题是回调函数是在该代码块之后执行的,因此您对该数据执行的所有操作都需要从该回调中调用,例如:

services.getHistorias(function(response){
        $scope.datos = response.data; // output array with data :)
        myFunction();
    })
...

function myFunction() {
    console.dir($scope.datos); //$scope.datos now available :)
}

其他代码块也是如此。

请记住有关回调/异步函数的这一点:仅仅因为一行代码位于另一行代码的正下方 - 这并不意味着它们会按该顺序执行

<小时/>

我现在将向您展示两个 super 简单的示例 - 一个错误的示例(就像您所做的那样),一个好的示例,使用 setTimeout 来模拟异步调用:

错误的

var data;

setTimeout(function() {
  data = 'I will not be available!';
}, 100);

alert(data); // undefined

<小时/>

正确的

var data;

setTimeout(function() {
  data = 'Que suerte!';
  showAlert();
}, 100);

function showAlert(){
  alert(data); // all good!
}

关于javascript - Angular $scope 在 Angular Controller 中的函数之外没有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31664355/

相关文章:

javascript - AppendChild 和 InsertBefore

javascript - 使用按钮而不是滑动的 ionic 滑动盒

javascript - ionic leaflet angularjs 指令 - 通过服务在侧边菜单中切换 tileLayer

angularjs - AngularJS中与路由相关的CSS页面过渡

AngularJS 如何使用路由删除 IE9 中的#符号

c# - 如何在调用 SQL Server 数据库调用的 Web 服务器上运行 AngularJS

AngularJs - 注入(inject) $scope

javascript - jQuery 放大/缩小完整的 div

javascript - 如何正确处理在 node-webkit 中打开 _blank 窗口的链接?

javascript - url 完成加载 View 后删除 localstorage