$http.get 和控制器之间的角度共享变量 [英] Angular Share Variable betwen $http.get and controller

查看:26
本文介绍了$http.get 和控制器之间的角度共享变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法将 $http.get() 中的一个变量的内容传递到此方法之外......它总是 undefined.

I can't pass the content of one variable inside $http.get() to outside of this method... it's always undefined.

我用 $rootScope 进行了测试,但是没有用.

I tested with $rootScope, but it didn't work.

controller('myControl', function ($scope, $http) {
    var content;

    $http.get('../Json/data.json').success(function (data, content) {
        content = data;
    }).error(function (data, status, headers, config) {
        $scope.dataJson = "ERROR";
    });

    console.log(content); 
});

推荐答案

这里有两个问题:

  • 成功处理程序中的 content 参数隐藏控制器中的 content 变量.
  • 您正试图在 content 具有值之前将其写入控制台.这将不起作用,因为 $http.get() 是异步的.
  • The content parameter in your success handler is shadowing the content variable in your controller.
  • You are trying to write content to the console before it has a value. This will not work because $http.get() is asynchronous.

要解决这些问题:

  • 删除 content 参数.它没有任何意义.
  • 使用content变量inside你的success回调.
  • Remove the content parameter. It serves no purpose.
  • Use the content variable inside your success callback.
controller('myControl', function ($scope, $http) {
    var content;

    $http.get('../Json/data.json').success(function (data) {
        content = data;

        console.log(content);
        $scope.dataJson = content;
    }).error(function (data, status, headers, config) {
        $scope.dataJson = "ERROR";
    });
});

这篇关于$http.get 和控制器之间的角度共享变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆