global variable Angularjs

Asked

Viewed 1,753 times

2

The question is simple, before the function I declared splited and within the alternate function splited for the value returned in response, now, after the function when I give console.log returns empty. Because?

var splited;
$scope.id = $routeParams.id;
shows.get($scope.id).then(function(response) {
  // splita url video to get only video id
  var video = response.video_url;
  splited = video.split("=")[1];
});
console.log(splited);
  • Try to declare the variable in $rootScope, I guess that solves your problem

2 answers

5

The function that is passed to the method then is not executed synchronously. It will only be executed when the output of shows.get is available.

But the line console.log(splited) is executed immediately after the call to shows.get. At that time, the function of the then has not yet been executed, and the value of its variable splited is at its original value (undefined).

  • 2

    Complementing, move the console into the .then() will show the correct value.

  • the problem is that I need to take the value of splited after calling the function, it is possible to run the function assycronamente?

  • The function is running asynchronously. You can only execute some code that depends on the value of the variable splitted after its value is calculated - as @Celsomtrindade suggested, place this logic within the function passed pro then, and not outside of it.

  • with this return of splited i call a youtube function that loads a player, but this player only appears after I give F5 on the page, because?

  • It’s probably in some process that doesn’t trigger Digest. Try adding this to the end of the function: '$Scope. $apply()' and see if it solves

0


Take a look at ngResource, an example I did on my service.

 var services = angular.module('ProcessoService', ['ngResource']);

    services.factory('ProcessosFactory', function($resource,apiUrl){
      var resource = $resource('http://restTest/retornos');

      var factory = {
          listar: function () {        
              var lista = resource.query({}, function(data){
                 lista = data;
              });
              return lista;
          }


      }


  return factory;

in controller only calls:

$Scope.list = Processosfactory.list();

This method serves to return a list or only an object.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.