Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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?

like image 476
Rasmus Avatar asked Apr 03 '14 12:04

Rasmus


1 Answers

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

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

Example:

angular.module('myapp').controller('myController', ($scope, Urls) {
  $scope.Urls = Urls;
}
like image 55
CarlosCondor Avatar answered Oct 13 '22 00:10

CarlosCondor