如何创建要在 Angularjs 中的控制器之间共享的全局常量? [英] How to create this global constant to be shared among controllers in Angularjs?

查看:27
本文介绍了如何创建要在 Angularjs 中的控制器之间共享的全局常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

angularjs-master-seed 中的 services.js 如下;

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

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

如何修改它以拥有一个可在控制器之间共享的常量 $webroot?

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?

推荐答案

如果您的变量具有恒定值或设置一次 value 是正确的选择.
你可以这样定义:

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

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

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

这篇关于如何创建要在 Angularjs 中的控制器之间共享的全局常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆