这是 How to create this global constant to be shared among controllers in Angularjs? 的后续问题
提供的答案允许在 Controller 之间共享常量 $webroot。
app = angular.module('myApp', []);
app.constant('$webroot', 'localhost/webroot/app');
app.controller('myController', ['$scope', '$webroot', function($scope, $webroot) {
$scope.webroot = $webroot;
}]);
但是,问题是如果我有 10 个常量,那么所有 10 个常量都必须注入(inject)到 Controller 中。这使得 Controller 声明看起来又长又难看。 如何在 AngularJS 中创建一个具有可在 Controller 之间共享的属性的对象?这样,我只需要注入(inject)一个对象而不是许多常量。这可以在 Angularjs 中完成吗?谢谢。
最佳答案
var app = angular.module('app', []);
app.constant('config', {
prop1: 'val1',
prop2: 'val2',
...
});
app.controller('Ctrl', ['config', function(config) {
console.log(config.prop1);
console.log(config.prop2);
...
}]);
关于javascript - 如何创建一个具有可在 AngularJS 中的 Controller 之间共享的属性的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22710593/