How to create this global constant to be shared among controllers in Angularjs?

前端 未结 2 1956
情深已故
情深已故 2020-12-11 13:35

Suppose I want to make this a variable a constant to be shared among controllers in Angularjs;

$webroot = \"localhost/webroot/app\"

After s

相关标签:
2条回答
  • 2020-12-11 14:26

    If your variable have a constant value or is set once value is the right choice.
    You can define it like this:

    app = angular.module('myApp', []);
    app.value('$webroot', 'localhost/webroot/app');
    

    Now you can inject the service to your controller and use it:

    app.controller('myController', ['$scope', '$webroot', function($scope, $webroot) {
      $scope.webroot = $webroot;
    }]);
    

    Edit #1
    To fit your updated question: You can use a constant the same way as a value:

    app = angular.module('myApp', []);
    app.constant('$webroot', 'localhost/webroot/app');
    
    app.controller('myController', ['$scope', '$webroot', function($scope, $webroot) {
      $scope.webroot = $webroot;
    }]);
    
    0 讨论(0)
  • 2020-12-11 14:27

    Whats happens when you want more constants? How about adding a config object that you can inject wherever needed. As its a single file it's also much easier to have dev.config and prod.config files that can be swapped in and out at build time.

    app.factory('Config', function(){
        return{
            webRoot: "localhost/webroot/app",
            moreSettings: "abc"
        };
    });
    
    0 讨论(0)
提交回复
热议问题