Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs service vars in all controller templates


I'am very new to Angularjs.
I created an Angularjs Service to store some "global" vars. It looks like this:

.factory('authVars', function() {
    var sdo = {
        baseBackendUrl: 'https://www.myurl.com',
        user: '',
        password: '',
        token: '',
        isLogged: false
    };
   return sdo;
})

Now I want use ng-show/hide in different controllers.

<div class="alert" ng-hide="authVars.isLogged">
    <strong>whatEver</strong>
</div>

Is this even possible? Or is it better to store this in the rootScope?
For a bit of help I would be very grateful ;-) thx

like image 843
chris Avatar asked Oct 16 '13 06:10

chris


3 Answers

Just register your factory to every controller. This is a goal service for code reuse. Service is like utility, you write it once and can use it in many controllers

JS

myApp.factory('authVars', function() {
    var sdo = {
        baseBackendUrl: 'https://www.myurl.com',
        user: '',
        password: '',
        token: '',
        isLogged: false
    }; 

    return {
        getSdo: function() {
            return sdo;
        }
    };

})


function MyCtrl($scope, authVars) {

    $scope.authVars = authVars.getSdo();
}

Demo Fiddle

like image 90
Maxim Shoustin Avatar answered Oct 14 '22 02:10

Maxim Shoustin


It is 100% ok to put it in service! Just don't forget to inject it in relevant controllers:

var Ctrl = function($scope,authVars){
    $scope.authVars = authVars;
}

Example: http://jsfiddle.net/cherniv/pzFrs/2/

like image 41
Ivan Chernykh Avatar answered Oct 14 '22 02:10

Ivan Chernykh


you need to inject service in controller as below.

  app.controller('ctrl',function($scope, authVars){          
    $scope.authVars=authVars;   
  });
like image 39
Nitu Bansal Avatar answered Oct 14 '22 02:10

Nitu Bansal