访问角度常量i脚本标记

时间:2018-01-18 15:34:37

标签: angularjs angular-constant

我有这个json文件,url.json:

{
  "security": 
    {
      "url": "https://url.to.securitypage/here"
    }     
}

我需要在HTML页面的脚本标记中访问该网址:

<script type="text/javascript">
        //Sends user to security page
        document.write('<link type="text/css" href="https://url.to.securitypage/here" rel="stylesheet"/>');
</script>

在模块中,我将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']);
    });
}

我想要的是:

<script type="text/javascript">
    //Sends user to security page
    document.write('<link type="text/css" href="URL.security.url" rel="stylesheet"/>');
</script>

我怎样才能轻松实现这一目标? 谢谢你的帮助,这对我来说是新的

1 个答案:

答案 0 :(得分:0)

document.write添加到成功处理程序:

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);
            var url = response.data;
            var link = `<link type="text/css" href=${url} rel="stylesheet"/>`
            document.write(link);
        }, function(error) {
            console.error(error);
    })
}