5
var referrer = $document.referrer;

Need the value of

$document.referrer 

in a variable.

Amit Verma
  • 40,709
  • 21
  • 93
  • 115
KRUNAL
  • 81
  • 1
  • 6

1 Answers1

3

$document is actually a jqLite/jQuery query result soi the property doesn't exists. If you want to get the referrer you can:

a) Access the DOM document directly:

var referrer = document.referrer; 

This is not recommended as you will fall in trouble writing unit tests.

b) Reference the object inside the jqLite/jQuery query result:

var referrer = $document[0].referrer;

Personally I do not like this approach either, the code becomes ugly and misleading.

c) Decorate $document:

myApp.config(function($provide){
  $provide.decorator('$document', function($delegate){

    $delegate.getReferrer = function() {return document.referrer;};

    // alternative you can create a property
    // Object.defineProperty($delegate, 'referrer', {  
    //   get: function() { return document.referrer; }
    // });

    return $delegate; 
  });
});

and then to get the referrer:

var referrer = $document.getReferrer();
//Or if you created a property...
//var referrer = $document.referrer;

I prefer this option because you can easily mock this object in unit tests and your code is easier to understand.

Alex Pollan
  • 863
  • 5
  • 13