S Panfilov
S Panfilov

Reputation: 17581

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?

Upvotes: 48

Views: 39395

Answers (4)

Fabio Bonfante
Fabio Bonfante

Reputation: 5198

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

 

Upvotes: 78

Nimo
Nimo

Reputation: 8304

Slightly similar to 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>

HTH

Upvotes: 19

merqlove
merqlove

Reputation: 3784

Also we can use helper, similar to ROR.

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

Upvotes: 1

raul
raul

Reputation: 620

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

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

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

And in the 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>

Upvotes: 16

Related Questions