我想将图像存储 URL 公开给 View ,以便我可以在所有我的 View 中使用它:
<img ng-src="{{storageUrl}}/logo.png"
现在我有配置服务,我将其注入(inject)到每个 Controller 中,然后公开 storageUrl
变量以通过 $scope
查看。
angular.module('myApp').controller('MyCtrl', [
'$scope',
'AppConfigService',
function ($scope, AppConfigService) {
$scope.storageUrl = AppConfigService.storageUrl;
}
但问题是,几乎在每个 Controller 中,我都需要注入(inject)此服务并将此变量公开给 View 。我不想重复太多代码。因此,我感兴趣的是通过其他方式将一些配置变量全局公开给 ALL View 。你有什么建议?
谢谢
最佳答案
“全局”范围方式
将其设置在$rootScope
上。尽管全局范围是不明智的。
此外,如果您必须使用全局作用域 ($rootScope) 来跟踪此情况,您可以在 run()
block 中设置它,一旦应用程序准备就绪,它将立即设置:
angular.module('myApp').run([
'$rootScope', 'AppConfigService',
function($rootScope, AppConfigService) {
$rootScope.storageUrl = AppConfigService.storageUrl
}
]);
全局作用域的问题是,您加载到应用程序中的任何其他模块都可以轻松地破坏 $rootScope 上的变量,并且很难调试。
更好的方法:直接在“外部 Controller ”中使用该服务:
app.controller('OuterCtrl', [
'$scope', 'AppConfigService',
function($scope, AppConfigService) {
$scope.config = AppConfigService;
}
]);
然后将整个应用程序包装在该 Controller 中:
<body ng-controller="OuterCtrl">
<div ng-controller="MyCtrl"> other stuff here </div>
</body>
为什么这有效?因为该 Controller 下的所有 Controller 和指令通常都从此 Controller 的作用域继承其作用域。
关于javascript - 注册可从 AngularJS 中的 VIews 访问的全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24642782/