Global variables in AngularJS

前端 未结 12 1821
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 12:05

I have a problem where i\'m initialising a variable on the scope in a controller. Then it gets changed in another controller when a user logs in. This variable is used to co

相关标签:
12条回答
  • 2020-11-22 12:24

    I just found another method by mistake :

    What I did was to declare a var db = null above app declaration and then modified it in the app.js then when I accessed it in the controller.js I was able to access it without any problem.There might be some issues with this method which I'm not aware of but It's a good solution I guess.

    0 讨论(0)
  • 2020-11-22 12:26

    You can also use the environment variable $window so that a global variable declare outside a controller can be checked inside a $watch

    var initWatch = function($scope,$window){
        $scope.$watch(function(scope) { return $window.globalVar },
            function(newValue) {
                $scope.updateDisplayedVar(newValue);
        });
    }
    

    Becareful, the digest cycle is longer with these global values, so it is not always real-timed updated. I need to investigate on that digest time with this configuration.

    0 讨论(0)
  • 2020-11-22 12:29

    Please correct me if I'm wrong, but when Angular 2.0 is released I do not believe$rootScope will be around. My conjecture is based on the fact that $scope is being removed as well. Obviously controllers, will still exist, just not in the ng-controller fashion.Think of injecting controllers into directives instead. As the release comes imminent, it will be best to use services as global variables if you want an easier time to switch from verison 1.X to 2.0.

    0 讨论(0)
  • 2020-11-22 12:30

    Try this, you will not force to inject $rootScope in controller.

    app.run(function($rootScope) {
        $rootScope.Currency = 'USD';
    });
    

    You can only use it in run block because config block will not provide you to use service of $rootScope.

    0 讨论(0)
  • 2020-11-22 12:32

    If you just want to store a value, according to the Angular documentation on Providers, you should use the Value recipe:

    var myApp = angular.module('myApp', []);
    myApp.value('clientId', 'a12345654321x');
    

    Then use it in a controller like this:

    myApp.controller('DemoController', ['clientId', function DemoController(clientId) {
        this.clientId = clientId;
    }]);
    

    The same thing can be achieved using a Provider, Factory, or Service since they are "just syntactic sugar on top of a provider recipe" but using Value will achieve what you want with minimal syntax.

    The other option is to use $rootScope, but it's not really an option because you shouldn't use it for the same reasons you shouldn't use global variables in other languages. It's advised to be used sparingly.

    Since all scopes inherit from $rootScope, if you have a variable $rootScope.data and someone forgets that data is already defined and creates $scope.data in a local scope you will run into problems.


    If you want to modify this value and have it persist across all your controllers, use an object and modify the properties keeping in mind Javascript is pass by "copy of a reference":

    myApp.value('clientId', { value: 'a12345654321x' });
    myApp.controller('DemoController', ['clientId', function DemoController(clientId) {
        this.clientId = clientId;
        this.change = function(value) {
            clientId.value = 'something else';
        }
    }];
    

    JSFiddle example

    0 讨论(0)
  • 2020-11-22 12:34
    // app.js or break it up into seperate files
    // whatever structure is your flavor    
    angular.module('myApp', [])    
    
    .constant('CONFIG', {
        'APP_NAME' : 'My Awesome App',
        'APP_VERSION' : '0.0.0',
        'GOOGLE_ANALYTICS_ID' : '',
        'BASE_URL' : '',
        'SYSTEM_LANGUAGE' : ''
    })
    
    .controller('GlobalVarController', ['$scope', 'CONFIG', function($scope, CONFIG) {
    
        // If you wish to show the CONFIG vars in the console:
        console.log(CONFIG);
    
        // And your CONFIG vars in .constant will be passed to the HTML doc with this:
        $scope.config = CONFIG;
    }]);
    

    In your HTML:

    <span ng-controller="GlobalVarController">{{config.APP_NAME}} | v{{config.APP_VERSION}}</span>
    
    0 讨论(0)
提交回复
热议问题