global variable angularjs

2

The question is simple, before the function I declare splited and within the function change splited to the value returned in response , now, after the function when I give console.log returns empty. Why?

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);
    
asked by anonymous 23.03.2016 / 18:00

2 answers

0

Take a look at ngResource, an example I made in 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 the controller it only calls:

$ scope.list = ProcessFactory.listar ();

This method is for returning a list or just an object.

    
08.04.2016 / 20:08
5

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

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

    
23.03.2016 / 18:06