How to get direct access to module constant in HTML in AngularJS

I want to use several constants directly in HTML (and several times in controllers).

For example, this is the main application 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, it’s clear how to use constants from controllers.

But how can I do something like this:

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

The bottom line is to store all the routes in one place. So can I do this, or have I chosen the wrong path?

+45
javascript angularjs
Jul 6 '13 at 17:03
source share
4 answers

IMHO, the best way to do this is to use $ rootScope. In html, every region inherits from $ rootScope, so if the variable is not in the current angular region, use the one declared in $ rootScope.

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

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

+78
Jul 06 '13 at
source share

A bit like other answers, but IMO cleaner:

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

and

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

NTN

+17
Oct 28 '15 at 14:11
source share

I also like the $ rootScope approach, but in some cases I used a filter.

As a simplified example, suppose that there is a CONFIG constant defined somewhere as an object with the BuildVersion property. You can create a filter like this:

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

And in HTML:

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

or

 <html ng-app="website"> <body> <div>{{'bla bla bla %VERSION%.' | interpolate}}</div> </body> </html> 
+16
Jul 11 '14 at 19:31
source share
+1
Aug 14 '14 at 10:10
source share



All Articles