How to use variable in more than one controller in AngularJS

1

I need to use a variable, in the angular, that I can use in more than one controller. Yes the controllers are in the same file. How can I do this?

.controller('denResCtrl', function($scope, $window, $http) {

$scope.fazerDenuncia = function (denuncia) {

    var diaDenun = formatarData(denuncia.dataDenun);
    var hora = denuncia.horaDenun;
    var tipo = denuncia.tipoDenun;
    var des = denuncia.descricao;

    var end = $window.localStorage.getItem('logradouro');
    var numeroEnd = denuncia.numeroEndereco;
    var cid = $window.localStorage.getItem('cidade');
    var estado = $window.localStorage.getItem('estado');

$http.get('http://localhost:8888/sistemas/webApps/ionic/vcApp/www/php/getCordenates.php?end='+end+'&numeroEnd='+numeroEnd+'&cid='+cid+'&estado='+estado).success(function (data) {
        var coordenadas = data;

    })

  }

})

The variables that are in the current controller, I created in it, and did not exist.

    
asked by anonymous 24.03.2016 / 19:26

2 answers

3

Use $ rootScope .

.controller('denResCtrl', function($scope, $window, $http, $rootScope) {
    $rootScope.forAnotherCtrl = 'some value';
})

.controller('AnotherCtrl', function($rootScope) {
    console.log($rootScope.forAnotherCtrl);
})
    
24.03.2016 / 20:16
5

You have two options for this: $ rootScope or a Service.

If you want to make a global variable for use in all controllers, you can use $ rootScope, which is the scope sharing between controllers.

A simple example would be to create a variable in the App.js in the run () method:

Note: I created this method because it runs when opening the application, but you can put a $ rootScope variable in any controller.

App.js

$ rootScope

.run(['$rootScope',
function ($rootScope) {

   $rootScope.variavelGlobal = "Teste";

}]);

To access the controller, just do this:

angular.module('MeuModulo')
    .controller('MeuController',
            ['$scope', '$rootScope',
                function ($scope, $rootScope) {

             console.log($rootScope.variavelglobal);

         //Isso pode ser feito também
         $rootScope.outraVariavelGlobal = "Teste2";                  
     }]);

Another solution would be to create a Service for this

angular.module('MeuModulo')
    .factory('MeuService', [function () {
            var aux = "";
            return {
                getMinhaVariavelGlobal: function () {
                    //Faz Alguma coisa aqui, busca de Um webservice, localStorage, etc..
                    aux = "Teste3";
                    return aux;
                }
            }
        }]);

And to get the value in the controller, just inject the service and call the function getMinhaVariavelGlobal ()

angular.module('MeuModulo')
    .controller('MeuController', function ($scope, MeuService) {
        var aux2 = MeuService.getMinhaVariavelGlobal();
        console.log(aux2);
    })
    
24.03.2016 / 20:17