javascript 在视图中访问 AngularJS 常量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22837360/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:51:01  来源:igfitidea点击:

Access AngularJS constant in a view

javascriptangularjscoffeescript

提问by Rasmus

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?

回答by CarlosCondor

Is not possible. You need to inject Urlsin the controller $scope(or parent using $parent) because {{ var }}is interpolated to $scope.var

不可能。您需要注入Urls控制器$scope(或使用的父级$parent),因为它{{ var }}被插入到$scope.var

Does not have any performance problem if you inject Urlsin your controller and write $scope.Urls = Urls

如果您注入Urls控制器并写入,则不会有任何性能问题$scope.Urls = Urls

Example:

例子:

angular.module('myapp').controller('myController', ($scope, Urls) {
  $scope.Urls = Urls;
}