Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...