0

I'm new to AngularJS, and I'm trying to use it to send a http get request to a remote server, without affecting any existing view code. I found a way to run a function immediately after html is ready, using stand alone init(). However when I code it like,

var init= function($http, $location) {
  //using $location to fetch query string

  if ($location.search().hasOwnProperty('a') && $location.search().hasOwnProperty('b')){
    var a= $location.search().a;
    var b= $location.search().b;

    var sendurl = 'http://someurl'+a+b ;

    var req = {
      method:'GET',
      url: sendurl,
      headers:{
        'Content-Type': 'text/html'
      },
      data: {token: ''}
    };

    $http(req)
      .success( function(){
        alert('success!');
      })
      .error(function(){
        alert("ERROR");
      });

  }
};
init() ;

In the console, the error is TypeError: $location is undefined. I know it must be I don't know how to utilize AngularJS code inside a stand alone function, so I'd like to ask how to write such function.

Community
  • 1
  • 1
tomriddle_1234
  • 3,145
  • 6
  • 41
  • 71

1 Answers1

1

try to write that function in service like this.

var myApp = angular.module('myApp', []);

myApp.factory('SomeService', function ($http, $location) {
  return {
    init: init
  };

  function init () {
    if ($location.search().hasOwnProperty('a') && $location.search().hasOwnProperty('b')){
      var a= $location.search().a;
      var b= $location.search().b;

      var sendurl = 'http://someurl'+a+b ;

      var req = {
        method:'GET',
        url: sendurl,
        headers:{
          'Content-Type': 'text/html'
        },
        data: {token: ''}
      };

      $http(req)
        .success( function(){
          alert('success!');
        })
        .error(function(){
          alert("ERROR");
        });
     }
   }
 });

and after call init function to the controller

  myApp.controller('MyController', function (SomeService){
     SomeService.init();
  });
donquixote
  • 365
  • 3
  • 10
  • How can I run this init() right after the view loaded? – tomriddle_1234 Jul 31 '16 at 12:38
  • @tomriddle_1234 depends on how your view is loaded. Is it view, that is loaded through route mapping, is it view bind to [`ngIf`](https://docs.angularjs.org/api/ng/directive/ngIf) construct, is it view used inside directive or maybe [`ngInclude`](https://docs.angularjs.org/api/ng/directive/ngInclude). – Eugene Jul 31 '16 at 12:45
  • bind controller to the view and when it loads controller will execute init function. Look at this documentation https://docs.angularjs.org/guide/controller#associating-controllers-with-angular-scope-objects – donquixote Jul 31 '16 at 12:48
  • @Eugene, actually, this http request has nothing to do with any view, I just want it run it once the view load or the url visited. – tomriddle_1234 Jul 31 '16 at 12:48