【问题标题】:Angular local variable to global variable角度局部变量到全局变量
【发布时间】:2016-10-28 12:00:43
【问题描述】:

我试图从 JSON 范围之外的 JSON 中获取国家/地区名称,但不知何故它似乎没有通过,我做错了什么?我查看了 $rootScope 但似乎并没有走得太远。原则上很简单,我想在其他作用域或页面本身上使用Country name作为变量,也想在Controller.cs(.net)中使用它发送到数据库

app.controller('PageController',
  function ($scope, $http) {

var analyticsCountry = "default";

$.getJSON('//www.geoplugin.net/json.gp?jsoncallback=?',

function (data) {
    $scope.testing = data;
    $scope.testing.country = data.geoplugin_countryName;
    //console.log($scope.testing.country);
    analyticsCountry = $scope.testing.country;
});

    console.log(analyticsCountry);

    $scope.GetTrendingCDsByCountry = function () {
        $http({
            method: 'Get',
            url: "/CD/GetTrending?id=" + analyticsCountry

        })
            .success(function (data, status, headers, config) {
                $scope.cds= data;
            })
            .error(function (data, status, headers, config) {
                $scope.message = 'Unexpected Error';
            });

    };  


});

【问题讨论】:

    标签: javascript angularjs json http geolocation


    【解决方案1】:

    如果你想要它在视图中。只需将其绑定到$scope 就可以了。正如@Suren Srapyan 所说,回调将在保存了值"default"console.log() 之后执行。

    app.controller('PageController',
      function ($scope, $http) {
    
    $scope.analyticsCountry = "default";
    $scope.GetTrendingCDsByCountry = function () {
        $http({
            method: 'Get',
            url: "/CD/GetTrending?id=" + $scope.analyticsCountry
    
        })
            .success(function (data, status, headers, config) {
                $scope.cds= data;
            })
            .error(function (data, status, headers, config) {
                $scope.message = 'Unexpected Error';
            });
    
    };  
    
    $.getJSON('//www.geoplugin.net/json.gp?jsoncallback=?',
    
    function (data) {
        $scope.testing = data;
        $scope.testing.country = data.geoplugin_countryName;
        //console.log($scope.testing.country);
        $scope.analyticsCountry = $scope.testing.country;
        console.log($scope.analyticsCountry);
        $scope.GetTrendingCDsByCountry();
      });
    
    });
    

    现在它可以工作了,并且可以在视图中轻松访问。

    【讨论】:

    • 是的,我知道如何做到这一点,我想如何将它作为变量传递,这样我也可以在 PageController.js 的其他 json 例程中使用它,而不是在本地使用查看
    • 这个$scope.analyticsCountry 也可以在您的pageController 中作为变量轻松访问。
    • 但是从http请求执行回调之后。
    • 我通过来自我的数据库的另一个请求对代码进行了一点扩展,以根据 IP 地址获取用户所在国家/地区的趋势 CD。也许现在我想做什么更清楚了
    • 完成了。查看代码。我刚刚在你的变量被定义后执行了这个函数
    猜你喜欢
    • 2017-11-08
    • 2019-07-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-05
    相关资源
    最近更新 更多