AngularJS作用域变量在页面加载中未定义其他功能

时间:2019-04-04 08:27:44

标签: 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();
});

2 个答案:

答案 0 :(得分:2)

您正在使用代码中的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();
            }
        });
    }

答案 1 :(得分:0)

尝试在GetGrades中调用函数then()

 $scope.GetCategories  = () => {
    $http
        ({
            method: 'GET',
            url: 'categories.json',
        })
        .then(data => {
            $scope.categories = data.data;
            $scope.drpCategory = $scope.categories[0].category
            $scope.GetGrades($scope.drpCategory)
        }, function errorCallback(response) {
            console.log(response);
            console.log('error');
        });
 }
 $scope.GetGrades = (drpCategory) => {
   $http
      ({
          method: "GET",
          url: "categories_" + drpCategory + ".json"
      }).then(function (response) {
          $scope.grades = response.data;
          console.log($scope.grades)
      });
}
 $scope.GetCategories()

工作示例:http://plnkr.co/edit/ZN8nI7OhAyWiJWlqeJsU?p=preview