Переменная области видимости AngularJS не определена при загрузке страницы для другой функции - PullRequest
1 голос
/ 04 апреля 2019

Я пытаюсь инициализировать переменную области действия с помощью 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 ]

2 голосов
/ 04 апреля 2019

Вы делаете асинхронный вызов, используя обещания в своем коде, поэтому $ scope.drpCategory может не загружаться при вызове функции GetGrades. Вы можете вызвать свою функцию GetGrades, когда решите GetCategories.

$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();
            }
        });
    }
0 голосов
/ 04 апреля 2019

Попробуйте вызвать функцию GetGrades in 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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...