如何在 AngularJS 的 HTML 中直接访问模块的常量 [英] How to directly access module's constant in HTML on AngularJS
问题描述
我想直接在 html 中使用几个常量(并在控制器中使用几次).
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?
推荐答案
恕我直言,更好的方法是使用 $rootScope在 html 中,每个范围都继承自 $rootScope,因此如果当前范围 angular 中不存在变量,请使用 $rootScope 中声明的变量.
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.
一个好方法是在运行阶段"
angular.module('myApp')
.run(function ($rootScope) {
$rootScope.ROUTES = ROUTES
});
这篇关于如何在 AngularJS 的 HTML 中直接访问模块的常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!