javascript - angular controller and http variable -


i have angular service uses $http json file.

app.factory('jsonfile', function($http) {     var promise;     var jsondata = {         get: function() {             if ( !promise ) {                 var promise =  $http.get('src/app_preprocess/data_json.js').success(function(response) {                     return response.data;                 });                 return promise;             }         }     };     return jsondata; }); 

and controller

app.controller('firstctrl', function (jsonfile , $scope) {     jsonfile.get().then(function(d) {         $scope.header = d.data.package.item[0]      }) }); 

this works well.

my question why can not add outcome of http variable instead of scope so...?

app.controller('firstctrl', function (jsonfile , $scope) {     var output;     output = jsonfile.get().then(function(d) {         return d.data.package.item     });     $scope.header = output[0]; }); 

because jsonfile returns promise , try use output before returns.. inside then clause can assured promise return in expected timing. outside of - can't due async nature of http calls.

you can read more promises in angular here


Comments

Popular posts from this blog

c# - How to get the current UAC mode -

postgresql - Lazarus + Postgres: incomplete startup packet -

javascript - Ajax jqXHR.status==0 fix error -