Marc M.
Marc M.

Reputation: 3791

AngularJS - How to Use Service in Template

I can access a service such as $routeParams from the controller like so.

angular.module('myModule', []).

    controller('myCtrl', ['$routeParams',
                          '$scope', function($routeParams,
                                             $scope) {

        console.log($routeParams['my-route-param']);                       

    }])

But how would I do the same from a template. I tried the following code to no avail.

<h1 ng-hide="$routeParams['my-route-param']">No route param!</h1>

I know you could always save the value to $scope, but I am looking for a cleaner solution.

Upvotes: 1

Views: 2105

Answers (2)

Steven
Steven

Reputation: 21

It's a bit late, but I had enough of copying $routeParams into my $scope only to be able to use them in my views, so I created a directive to do so.

Let's say you have this routing config:

...
angular.module( 'myApp' ).config( [ '$routeProvider', function( $routeProvider ) {
    $routeProvider.when( '/view1/:param1/:param2', {
        templateUrl: 'view1/view1.html',
        controller: 'View1Ctrl'
    });  
}])
...

And in your view1.html:

<h1 isteven-rr>$routeParams says: [[param1]] [[param2]]</h1> 

If you have this in your URL bar: http://localhost/#/view1/Hello/World!

Then you'll see:

$routeParams says: Hello World!

Fork & learn more: https://github.com/isteven/angular-route-rage

Hope it can help shorten development time! Cheers!

Upvotes: 0

vittore
vittore

Reputation: 17589

You can assign routeParams to a property of $scope:

controller('myCtrl', ['$routeParams',
                      '$scope', function($routeParams,
                                         $scope) {
 ...
 $scope.$routeParams = $routeParams
 ...
 }

and then this would work:

 <h1 ng-hide="$routeParams['my-route-param']">No route param!</h1>

Reason for that is every property you are accessing from template should be defined in current scope, which of course is not the case for parameter of controller constructor.

NB: in case of controller as syntax used you would do the same with controller, not scope:

controller('myCtrl', ['$routeParams',
                      '$scope', function($routeParams,
                                         $scope) {
 ...
 this.$routeParams = $routeParams
 ...
 }

and markup:

 <div ng-controller="myCtrl as ctrl">

     <h1 ng-hide="ctrl.$routeParams['my-route-param']">No route param!</h1>

Upvotes: 2

Related Questions