Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to use several 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 how can I do something like this:

<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?

like image 776
Sergei Panfilov Avatar asked Jul 06 '13 17:07

Sergei Panfilov


People also ask

Can I use const in AngularJS?

We can inject Constant everywhere in controller or service like any other dependency (e.g.$http). AngularJS used Singleton structure for creating Constant dependency in our Angular application. So, using the Constant you can create your Config. js file and can be inject anywhere in your application.

How does HTML work with AngularJS?

How AngularJS works with HTML. The AngularJS framework works by first reading the HTML page (which has additional attributes). Angular then interprets those attributes as directives to bind input or output parts of the page to a model represented by standard JS variables.


1 Answers

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 way is to initialize this in the run "phase"

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

 

like image 65
Fabio Bonfante Avatar answered Oct 01 '22 04:10

Fabio Bonfante