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

查看:135
本文介绍了如何创建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主种子的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?

我可以做以下?

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?

推荐答案

如果您的变量有一个常数或曾经设定是正确的选择。结果
你可以将其定义是这样的:

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天全站免登陆