如何在HTML的script标签中访问Angular常量中的JSON URL?
用Angular Constant动态添加样式表的简单实现
首先得说,你原来想用document.write直接拿URL常量的思路走不通——那个<script>是在Angular启动前就执行的,这时候你预加载的URL常量还没被注册到Angular里呢,根本访问不到。
不过别担心,结合你已经做好的预加载步骤,咱们用Angular本身的方式就能轻松实现需求,而且更符合框架规范:
步骤1:保留你已有的预加载代码
你之前写的预加载url.json并注册URL常量的代码没问题,继续保留:
var myApp = angular.module('myApp', []); getUrl().then(bootstrapApplication()); function getUrl() { var initInjector = angular.injector(['ng']); var $http = initInjector.get('$http'); return $http.get('./url.json') .then(function(response) { myApp.constant('URL', response.data); }, function(error) { console.error(error); }) } function bootstrapApplication() { angular.element(document).ready(function() { angular.bootstrap(document, ['myApp']); }); }
步骤2:添加Run块动态插入样式表
在你的模块里添加一个run块——这是Angular启动后会立即执行的代码块,能直接拿到你注册好的URL常量,我们在这里动态创建样式链接并插入到页面中:
myApp.run(['URL', '$document', function(URL, $document) { // 创建link元素 var styleLink = angular.element('<link>'); // 设置link的属性 styleLink.attr({ type: 'text/css', rel: 'stylesheet', href: URL.security.url }); // 把link插入到head标签里 $document.find('head').append(styleLink); }]);
为什么不推荐全局变量的方式?
如果你非要在原来的<script>里用,也可以在预加载的时候把URL存到全局变量里(比如window.globalUrl = response.data),然后在script里写href="'+window.globalUrl.security.url+'",但这种方式会污染全局作用域,不符合Angular的设计理念,不建议使用。
这样一来,你就不需要那个硬编码的document.write代码了,Angular启动后会自动帮你把样式表加载进来,完全实现动态获取URL的需求~
内容的提问来源于stack exchange,提问作者chichi
相关产品推荐
相关产品推荐

