javascript - service gets URL for $http API request from controller - Angular.js -


i want service grabs info api after clicking html element.

"freegeoip.net/json/" + ip_address 

the problem is, service , url above being called before click occurs.

app.service("ips", function ($http, $q) {     // grab json     var deferred = $q.defer();     $http.get("http://www.freegeoip.net/json/" + ip_address).then(function (data)     {         deferred.resolve(data);     });      this.getitems = function ()     {         console.log(deferred.promise);         return deferred.promise;     } }) 

can show me can define variable ip_address later in click?

///inside controller

promise.then(function (data) {     $scope.items = data.data.items; }); $scope.defineip= function(item) {    ip_address = "212.38.168.60"    return ip_address; } 

the problem here have no clue how take value defined ip_address , inject service.

your code should go this.

app.service("ips", function ($http) {     this.getitems = function (ip_address) {        return  $http.get("freegeoip.net/json/" + ip_address)     } }); 

and in controller :

$scope.defineip= function(){    var ip_address = "212.38.168.60"    ips.getitems(ip_address).then(function(response){      console.log(response);    })  } 

dont forget add "ips" di in controller.

as want grab info on click of html element should call below:

 <button ngclick="defineip()">click here</button> 

you dont need inject $q in service $http returns promise object can use .then() method directly in controller


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -