Init function in AngularJS that calls another function and that return undefined -


i'm confused since can't figure out why varialbe fccdisplayname "undefined". created function, made api call, assigned vlue fccdisplayname; value. when function called within init function, undefined.

i guess has "scope", can't find why. here don't use $scope, "controller as".

your or hint highly appreciated

(function(){        var app = angular.module('twitch', []);         app.controller('twitchcontroller', ['$http', function($http){            var twitchapi = 'https://api.twitch.tv/kraken/';      var fccurl = 'users/freecodecamp';      var fccdisplayname;            var getfcc = function(){        $http({          method: 'get',          url: twitchapi+fccurl          }).then(function successcallback(response) {                fccdisplayname = response.data.display_name;                fccbio = response.data.bio;               }, function errorcallback(response) {                console.log(response);        });      }            var init = function(){  	  getfcc();        console.log(fccdisplayname);      }            //we init app      init();                }]);      })();
<html>    <head>      <script src="https://code.angularjs.org/1.3.14/angular.min.js"></script>      </head>    <body ng-app="twitch">        <div ng-controller="twitchcontroller twitch">         <div class="col-md-6 col-lg-6 item" id="freecodecamp">            {{testangular}}            <h2>{{fccdisplayname}} channel</h2>        </div>  </div>            </body>  </html>

you trying use fccdisplayname before asynchronous service request completed. need perform action inside of .then() resolution of request.

once you've received response, need bind this context since using controlleras.

var vm = this;  var getfcc = function(){     $http({         method: 'get',         url: twitchapi+fccurl     }).then(function successcallback(response) {         vm.fccdisplayname = response.data.display_name;         fccbio = response.data.bio;           console.log(vm.fccdisplayname);     }, function errorcallback(response) {         console.log(response);     }); }  var init = function(){     getfcc(); } 

update html binding point towards controlleras variable.

<div ng-controller="twitchcontroller twitch">        <div class="col-md-6 col-lg-6 item" id="freecodecamp">           {{testangular}}           <h2>{{twitch.fccdisplayname}} channel</h2>       </div> </div>  

Comments

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -