Pass URL to as $routeParam in AngularJS app

Rafal Pastuszak picture Rafal Pastuszak · Apr 27, 2013 · Viewed 29.8k times · Source

How can I pass actual URL (with slashes, commas, etc.) as a $routeParam to AngularJS App?

this will work: http://paprikka.github.io/le-bat/#/preview/asdadasda

this won't: http://paprikka.github.io/le-bat/#/preview/http://page.com

neither will this: http://paprikka.github.io/le-bat/#/preview/http%3A%2F%2Fpage.com

or this: http://paprikka.github.io/le-bat/#/preview/?url=http%3A%2F%2Fpage.com

Details

AngularJS routing mechanism by its design does not allow to pass strings with slashes as query parameters. I can understand the reasoning behind this decision - we don't want to create a stateless server here.

However, there are still cases when using different separators or regular expressions in routes might be necessary.

I wanted to create an app that takes a url hash string parameter and loads its content to an iframe (link here). Routes are set up in pretty standard way (I'm using Coffeescript, but this snippet does not differ from pure js):

$routeProvider
  .when('/preview/:src', {templateUrl: 'partials/preview.html',
  controller: 'PreviewCtrl'})
  .when('/preview', {templateUrl: 'partials/preview.html',
  controller: 'PreviewCtrl'})

Of course, I can load url from hash before AngularJS gets bootstrapped and then pass it to the library, but it would be nice if I could also update current route parameter when changing data in scope - that's why I think it's much better not to avoid AngularJS API.

Answer

mattwad picture mattwad · Nov 19, 2013

Using $routeProvider in Angular 1.2, you can pass in a url if it's at the end of the path by adding an asterik to the pattern. The following should work whether or not you URLComponentEncode the url.

The route:

angular.module('angularApp', ['ngRoute'])
      .when('/frame/:picture_url*', {
        templateUrl: 'views/frame.html',
        controller: 'PictureFrame'
      });

The controller:

      .controller('PictureFrame', function($scope, $routeParams, $sce){
        //whitelist the URL
        $scope.picture_url = $sce.trustAsResourceUrl($routeParams.picture_url);
      });

Then in your template:

<iframe ng-src="{{picture_url}}"></iframe>