首页 > 解决方案 > AngularJS范围变量在其他功能的页面加载中未定义

问题描述

我试图在第一个函数的页面加载中通过http get请求初始化范围变量,但是当尝试在同一页面加载的其他函数中使用范围变量时,它是未定义的。

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

    $scope.GetCategories = function () {
        $http({
            method: 'GET',
            url: '/GradeAndSection/GetCategories'
        }).then(function (response) {
            $scope.categories = response.data;
            if (response.data != null) {
                $scope.drpCategory = $scope.categories[0].categoryID;
                                    }
        });
    };

    $scope.GetGrades = function () {
        \\$scope.drpCategory; here; is; undefined;
        $http({
            method: 'GET',
            url: '/GradeAndSection/GetGrades?categoryID=' + $scope.drpCategory
        }).then(function (response) {
            $scope.grades = response.data;
        });
    };

    $scope.GetCategories();
    $scope.GetGrades();
});

标签: angularjs

解决方案


您正在代码中使用 Promise 进行异步调用,因此在调用 GetGrades 函数时可能不会加载 $scope.drpCategory。解决 GetCategories 后,您可以调用 GetGrades 函数。

$scope.GetCategories = function () {
        $http({
            method: "GET",
            url: "/GradeAndSection/GetCategories"
        }).then(function (response) {
            $scope.categories = response.data;
            if (response.data != null) {
                $scope.drpCategory = $scope.categories[0].categoryID;
                $scope.GetGrades();
            }
        });
    }

推荐阅读