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

限于喜欢 提交于 2019-11-27 07:31:16

问题


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

$webroot = "localhost/webroot/app"

After some investigation, it seems services are the way to do. But what is the best way? Do I use a factory, service, value or something else?

The services.js from angularjs-master-seed is below;

angular.module('myApp.services', []).value('version', '0.1');

How do I modify it to have a constant $webroot that is sharable among controllers?

Can I do the following?

angular.module('myApp.services', [])
        .value('version', '0.1')
        .constant('webroot','localhost/webroot/app');

If it is ok, how do I call it in the controller?


回答1:


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;
}]);



回答2:


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"
    };
});


来源:https://stackoverflow.com/questions/22707699/how-to-create-this-global-constant-to-be-shared-among-controllers-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!