如何在Angularjs中创建这个全局常量,以便在控制器之间共享

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

本文关键字:之间 共享 常量 控制器 Angularjs 创建 全局      更新时间:2023-09-26

假设我想让这个变量成为Angularjs中控制器之间共享的常量;

$webroot = "localhost/webroot/app"

经过一番调查,服务似乎是解决问题的方法。但是什么是最好的方法呢?我是使用工厂、服务、价值还是其他东西?

angularjs-master-seed中的services.js在下面;

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

我如何修改它有一个恒定的$webroot是控制器之间共享?

我可以做以下事情吗?

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

如果ok,我如何在控制器中调用它?

当你想要更多的常量时会发生什么?添加一个可以在任何需要的地方注入的配置对象怎么样?因为它是一个单一的文件,所以dev.config和prod.config文件也更容易在构建时交换进出。

app.factory('Config', function(){
    return{
        webRoot: "localhost/webroot/app",
        moreSettings: "abc"
    };
});

如果您的变量有一个常量值或设置一次value是正确的选择。
你可以这样定义它:

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

现在你可以将服务注入到你的控制器中并使用它了:

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

编辑# 1
为了符合您的更新问题:您可以像使用值一样使用常量:

app = angular.module('myApp', []);
app.constant('$webroot', 'localhost/webroot/app');
app.controller('myController', ['$scope', '$webroot', function($scope, $webroot) {
  $scope.webroot = $webroot;
}]);