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


i have following example code in learning app. service job , pulls data out of page json code generated php, far 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 call getformules function in controller , put data inside $scope.formuleitems , test if succeeded , 'o no'... $scope.formuleitems = undefined! - strange because view showing data?

part of controller:

    dataloader.getformules(function (items){          $scope.formuleitems = items.data;      });      console.log('+++++++++++++++++', $scope.formuleitems); // gives undefined 

the first thing did search around on stackoverflow if else had same issue, , there was: undefined variable inside controller function.

i know there walkarounds this, i've done own research, tells me (see example below) isn't best way solve problem.

solution one: put $watch inside of controller

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

or even:

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

the rest of controller relying on $scope.formuleitems. have put $watch or if? can fix promise? never did before appreciated.

the code in callback

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

is evaluated asynchronously. means first fire request, javascript keeps on executing lines of code, hence performs

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

at point callback not invoked yet, because takes time , can happen @ point. execution not stopped this. therefore value of $scope.formuleitems still undefined, of course.

after - @ not defined time in future (probably few milliseconds later) callback invoked , value of $scope.formuleitems changed. have log value inside of callback-function.

you urgently have understand concept if want succeed in javascript, because happens on , on again :)


Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

c - Unrecognised emulation mode: elf_i386 on MinGW32 -