[英]Access AngularJS constant in a view
I'm gonna try to describe the scenario, bear with me please. 我要试着描述这个场景,请跟我说。
I have a Angular constant called Urls filled with the routes and some methods to access them. 我有一个名为Urls的Angular常量,它填充了路由和一些访问它们的方法。
app = angular.module "app"
app.constant "Urls",
routes:
# Main stuff
overview: "/"
users: "/users"
user: "/users/:id"
overview: ->
return @.routes.overview
users: ->
return @.routes.users
user: (id)->
return @.routes.user
.replace(":id", id)
The reason for using a constant for this is that I need to access it during the config phase of our application as well as use it in controllers. 为此使用常量的原因是我需要在应用程序的配置阶段访问它以及在控制器中使用它。
What I want to achieve is that I want to use it in a view as well, for instance; 我想要实现的是,我想在视图中使用它,例如;
<ul class="foo">
<li ng-repeat="user in users">
<a href="{{Urls.user(user.id)}}">
{{user.name}}
</a>
</li>
</ul>
Is there a way to achieve something like this? 有没有办法实现这样的事情? Preferably without assigning the Urls constant to $rootScope or assigning it to every controllers $scope?
最好不将Urls常量赋给$ rootScope或将其分配给每个控制器$ scope?
Is not possible. 不可能。 You need to inject
Urls
in the controller $scope
(or parent using $parent
) because {{ var }}
is interpolated to $scope.var
您需要在控制器
$scope
(或使用$parent
)中注入Urls
,因为{{ var }}
被内插到$scope.var
Does not have any performance problem if you inject Urls
in your controller and write $scope.Urls = Urls
如果你注入没有任何性能问题
Urls
在控制器和写$scope.Urls = Urls
Example: 例:
angular.module('myapp').controller('myController', ($scope, Urls) {
$scope.Urls = Urls;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.