如何创建要在 Angularjs 中的控制器之间共享的全局常量?

编程入门 行业动态 更新时间:2024-10-26 02:32:14
本文介绍了如何创建要在 Angularjs 中的控制器之间共享的全局常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

假设我想让这个变量成为一个常量,以便在 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-21 15:01:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1005300.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:常量   要在   全局   控制器   Angularjs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!