48

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?

S Panfilov
  • 16,641
  • 17
  • 74
  • 96

4 Answers4

79

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

 

Fabio Bonfante
  • 5,128
  • 1
  • 32
  • 37
  • I think this should be a concept that everyone attempts to understand before they go writing any controllers. I don't know how many times i've worked on a controller with scope and rootscope loaded into it. – CarComp May 20 '15 at 14:15
  • 7
    Keep in mind that the value defined in `$rootScope` will not be accessible directly in directives with isolated scopes. In such cases you can get this value with `$root.ROUTES` in the view. – fracz Dec 17 '15 at 07:33
19

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

Nimo
  • 7,984
  • 5
  • 39
  • 41
16

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>
raul
  • 620
  • 6
  • 14
  • I almost used this because it was familiar, and it's a good answer, but I do think the accepted answer is better overall. Upvoted both. – VSO Mar 16 '16 at 17:34
1

Also we can use helper, similar to ROR.

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

merqlove
  • 3,674
  • 1
  • 23
  • 22