0

I am using the following code:

var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "/Scripts/Pages/Home.js", false);
xmlhttp.setRequestHeader("X-Custom-Header", "My Values");
xmlhttp.send();
var m = document.createElement('script');
m.appendChild(document.createTextNode(xmlhttp.responseText));
document.getElementsByTagName('head')[0].appendChild(m);

Can someone advise me if it is possible to get a javascript with $http and show me how I can do it inside a function that returns a promise when it is completed. The reason I would like to use $http is that along with the request for the js I need to send a custom header for authorization.

Please note that this question is different from the one suggested as a duplicate in that I am also wanting to find out if I can get a javascript and add it to the page DOM in the same way as it was done with the .setRequestHeader. Thanks

Samantha J T Star
  • 30,952
  • 84
  • 245
  • 427
  • 1
    $http is just ajax,so if you can with raw ajax you with $http. – mpm Jun 02 '14 at 07:16
  • 1
    Please see this example http://stackoverflow.com/questions/11876777/angularjs-set-http-header-for-one-request – Chandermani Jun 02 '14 at 08:27
  • @Chandermani - Thanks for the link. But I already know how to do the header. My problem is I am not sure how to correctly contain the call to the $http in a function, have it return a script that gets added to the document and have the function return a promise when completed. Do you have any ideas how I could do this as that would answer my question. Thanks. – Samantha J T Star Jun 02 '14 at 09:04

1 Answers1

1

Since $http is a implementation for XMLHttpRequest in Angular, you can of course make requests to get the contents of a JS file.

You can set additional headers with $http like this:

$http({
  method: 'get',
  url: 'some/js/file.js',
  headers: {
    "X-Custom-header": "foo"
  }
}).then(function (data) {
  // do something with the DOM here
});

So as you can see, you are actually able to do that.

Pascal Precht
  • 8,803
  • 7
  • 41
  • 53
  • Thanks but how can I attach that script to my DOM and make it so the javascript code inside that was fetched from the file "file.js" runs? My problem is I am not sure how to attach it. – Samantha J T Star Jun 02 '14 at 10:17
  • 1
    You can do it like you always did. It's still just JavaScript. – Pascal Precht Jun 02 '14 at 11:09
  • PascalPrecht - So do I have to attach it to the DOM? Sorry but I'm not sure I understand. I would appreciate if you can show me with the answer. Thank you. – Samantha J T Star Jun 02 '14 at 11:15