我可以直接从HTML下AngularJS接入模块不变 [英] Can i directly access module constant from HTML under AngularJS

查看:148
本文介绍了我可以直接从HTML下AngularJS接入模块不变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用几个常量直接在HTML,并几次在控制器。
例如,这是主要的应用程序模块:

I want to use few constants directly in html, and few times in controllers. For example, this is main app module:

angular.module('website', [])
.constant('ROUTES', (function () {
    return {
        SIGN_IN: '/sign/in'
  }
})())
.config([..., 'ROUTES', function(..., ROUTES {
    $routeProvider.when(ROUTES.SIGN_IN, {templateUrl: 'pages/sign_in.html', controller:     'SignInController'});
}]);

因此​​,这是明确的,如何使用常量从控制器。
但是,我可以这样做:

So this is clear, how to use constants from controllers. But can i do something like:

<html ng-app="website"> 
<body>
<a href="{{ROUTES.SIGN_IN}}">Sign in</a>
</body>
</html>

问题的关键是保持所有路由在同一个地方。
所以,我可以做到这一点,也可能是我选用走错了路?

The point is to keep all routes in one place. So, can i do this, or may be i choosed wrong way?

推荐答案

恕我直言更好的方式来做到这一点是使用的 $ rootScope
在HTML中每一个范围从$ rootScope继承,所以如果一个变量不是在当前范围内使用角度一个在$ rootScope宣布present。

IMHO the better way to do this is use the $rootScope In html every scope inherits from the $rootScope, so if a variable isn't present in the current scope angular use the one declared in $rootScope.

一个很好的(恕我直言)方法是初始化这个的运行相中

A good (IMHO) way is to initialize this in the run "phase"

angular.module('myApp')
  .run(function ($rootScope) {
      $rootScope.ROUTES = ROUTES
   });

&NBSP;

这篇关于我可以直接从HTML下AngularJS接入模块不变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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