在AngularJS表达式中调用全局变量 [英] Call Global Variable in AngularJS Expression

查看:91
本文介绍了在AngularJS表达式中调用全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在head标签中有一些全局变量:

I have some global variables in head's tag:

<script type="text/javascript">
    var apiRoot = 'http://localhost:8000/api',
        apiUrl = apiRoot,
        apiBadgeUrl = apiRoot + '/badges',
        apiLevelUrl = apiRoot + '/levels',
        apiBehaviorUrl = apiRoot + '/behaviors',
        apiTrophyUrl = apiRoot + '/trophies',
        apiUserUrl = apiRoot + '/users',
        apiWidgetPreferencesUrl = apiRoot + '/widgetPreferences';
</script>

我想在html文件中使用角度表达式,但我的尝试失败了:

I want to use in angular expression in html file but my tries are fails:

{{ $window.apiRoot }} or {{ apiRoot }} 


推荐答案

这些表达式是针对当前范围进行评估的。如果您尚未通过控制器在示波器中设置它们,则无法进行评估。请参阅 http://docs.angularjs.org/guide/expression

These expressions are evaluated against the current scope. If you have not set them in your scope via a controller, it will not evaluate. See http://docs.angularjs.org/guide/expression

示例:

function MyCtrl($scope)
{
   $scope.apiRoot = apiRoot;
}

HTML:

<div ng-controller="MyCtrl">
   {{apiRoot}}
</div>

如前所述,虽然上述示例有效,但不建议使用。更好的方法是在服务中设置这些变量,然后让它们通过服务。

As has been mentioned, while the above example works, it is not reccommended. The better way would be to set these variables in a service and then get them through the service.

function MyCtrl($scope, apiRootService)
{
   $scope.apiRoot = apiRootService.getApiRoot();
}

服务:

angular.module('myServices', []).factory('apiRootService', function() {
    var apiRoot = 'http://localhost:8000/api',
    apiUrl = apiRoot,
    apiBadgeUrl = apiRoot + '/badges',
    apiLevelUrl = apiRoot + '/levels',
    apiBehaviorUrl = apiRoot + '/behaviors',
    apiTrophyUrl = apiRoot + '/trophies',
    apiUserUrl = apiRoot + '/users',
    apiWidgetPreferencesUrl = apiRoot + '/widgetPreferences';
    return {
      getApiRoot: function() {
         return apiRoot
      },
      //all the other getters
   });

这篇关于在AngularJS表达式中调用全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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