如何直接访问模块's在AngularJS上的HTML中的常量

How to directly access module's constant in HTML on AngularJS

本文关键字:上的 AngularJS HTML 常量 访问 何直接 模块      更新时间:2023-09-26

我想直接在html中使用几个常量(在控制器中使用几次)。

例如,这是主要的应用程序模块:

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'});
}]);

所以这很清楚,如何使用控制器中的常量。

但是我怎么能做这样的事情:

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

关键是要把所有路线都放在一个地方。那么,我可以这样做吗,或者我选择了错误的方式?

IMHO更好的方法是使用$rootScope在html中,每个作用域都继承自$rootScope,因此,如果当前作用域angular中不存在变量,请使用$rootScope中声明的变量。

一个好的方法是在运行";阶段";

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

与其他答案略有相似,但IMO更清洁:

angular.module('website')
    .constant("ROUTES", {
        SIGN_IN: "/sign/in"
    })
    .run(function ($rootScope, ROUTES) {
        $rootScope.ROUTES = ROUTES;
    });

和:

<a href="{{ROUTES.SIGN_IN}}">Sign in</a>

HTH

我也喜欢$rootScope方法,但在某些情况下我使用了过滤器。

作为一个简化的例子,假设某个地方有一个常量CONFIG定义为一个具有BuildVersion属性的对象。你可以创建一个类似这样的过滤器:

angular.module('myApp')
  .filter('interpolate', ['CONFIG', function (CONFIG) {
      return function (text) {
          return String(text).replace(/'%VERSION'%/mg, CONFIG.BuildVersion);
      };  
  }]);

在HTML中:

<html ng-app="website"> 
    <body>
        <div>{{'%VERSION%' | interpolate}}</div>
    </body>
</html>

<html ng-app="website"> 
    <body>
        <div>{{'bla bla bla %VERSION%.' | interpolate}}</div>
    </body>
</html>

我们还可以使用类似于ROR的助手。

https://gist.github.com/merqlove/491023bcdd2145eef169#file-readme md