How to use variable in more than one controller in Angularjs

Asked

Viewed 8,025 times

1

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

.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 on it, and did not exist.

2 answers

5

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

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

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

Note: I created this method because it runs when opening the application, but you can put a variable in $rootScope 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 that reason

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 getMinhaVariavelGlobal function()

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

3


Use $rootScope.

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

.controller('AnotherCtrl', function($rootScope) {
    console.log($rootScope.forAnotherCtrl);
})
  • Bá! $rootScope is very bearded by what I see. E Marco, what Geferson put in the app.js file a . run and such, would serve if I want to declare a global variable for the whole project, is that it? Or the way you did, also serves?

  • 1

    It also does. It is available throughout your project, but only after this variable is set. However, using it in the run() method or as mentioned by Geferson, the variable is defined at the time the application is initialized.

  • Okay, Marcos, I get it. Returning your answer, then, all the variables I created, in this controller, I have to take the var and put $rootScope.variableCreated, right?

  • If you want them to be available in another controller, yes, that’s right!

  • In addition, just don’t forget to inject the $rootScope dependency into the controller, otherwise I bet it will give rsrsrs error

Browser other questions tagged

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