$scope variable is undefined when it is set inside a function

妖精的绣舞 提交于 2020-01-04 05:17:14

问题


I have the following example code in my learning app. The service does his job and pulls some data out of a page with json code generated by php, so far so good.

service:

(function() {
    'use strict';

    angular
        .module('app.data')
        .service('DashboardService', DashboardService);

    DashboardService.$inject = ['$http'];
    function DashboardService($http) {

        this.getFormules = getFormules;

        ////////////////

        function getFormules(onReady, onError) {
            var formJson = 'server/php/get-formules.php',
                formURL  = formJson + '?v=' + (new Date().getTime()); // Disables cash

            onError = onError || function() { alert('Failure loading menu'); };

            $http
                .get(formURL)
                .then(onReady, onError);
        }

    }
})();

Then i call the getFormules function in my controller and put all the data inside my $scope.formuleItems and test if everything succeeded and 'o no'... $scope.formuleItems = undefined! - Strange because my view is showing data?

part of the controller:

    dataLoader.getFormules(function (items){

        $scope.formuleItems = items.data;

    });

    console.log('+++++++++++++++++', $scope.formuleItems); // gives undefined

The first thing i did was search around on stackoverflow to look if someone else had the same issue, and there was: Undefined variable inside controller function.

I know there are some walkarounds for this, i've done my own research, but something tells me that this (see example below) isn't the best way to solve this problem.

solution one: put $watch inside of the controller

$scope.$watch('formuleItems', function(checkValue) {
   if (checkValue !== undefined) {
     //put the code in here!
  }
}

or even:

if($scope.formuleItems != null) {}

The rest of the controller is relying on $scope.formuleItems. Do i really have to put everything into that $watch or if? Can i fix this with a promise? I never did that before so some help would be appreciated.


回答1:


The code in your callback

function (items){
    $scope.formuleItems = items.data;
}

is evaluated asynchronously. That means you first fire the request, then javascript keeps on executing your lines of code, hence performs

console.log('+++++++++++++++++', $scope.formuleItems); // gives undefined

At this point the callback was not invoked yet, because this takes some time and can happen at any point. The execution is not stopped for this. Therefore the value of $scope.formuleItems is still undefined, of course.

After that - at some not defined time in the future (probably a few milliseconds later) the callback will be invoked and the value of $scope.formuleItems will be changed. You have to log the value INSIDE of your callback-function.

You urgently have to understand this concept if you want to succeed in JavaScript, because this happens over and over again :)



来源:https://stackoverflow.com/questions/34660284/scope-variable-is-undefined-when-it-is-set-inside-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!