如何创建具有可在 AngularJS 中的控制器之间共享的属性的对象? [英] How to create a object with properties that are sharable among controllers in AngularJS?

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

问题描述

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

提供的答案允许在控制器之间共享常量 $webroot.

The answer provided allows a constant $webroot to be shared among controllers.

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

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

然而,问题是如果我有 10 个常量,那么所有 10 个常量都必须注入控制器.这使得控制器声明看起来又长又丑.如何创建一个对象,其属性可在 AngularJS 中的控制器之间共享? 这样,我只需要注入单个对象而不是许多常量.这可以在 Angularjs 中完成吗?谢谢.

However, the problem is if I have 10 constants, then all 10 constants have to be injected into the controller. This makes the controller declaration look long and ugly. How can I create an object with properties that are sharable among controllers in AngularJS? In this way, I need only inject a single object instead of many constants. Can this be done in Angularjs? Thanks.

推荐答案

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

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

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