Given the following angularjs service:
angular.module('myApp.services', [])
.factory('EmployeesService', ['$http', function ($http) {
return {
name: 'Employees Service',
getByTerm: function (term, callback) {
$http.get('Services/GetEmployess?term='+term).success(function (data) {
callback(data);
});
}
};
} ]);
How can I set the $http.get URL to be dynamic and not hard-coded?
Not sure what part of the url you want to be dynamic, so this is if you want the "term=" + term part to be dynamic:
angular.module('myApp.services', [])
.factory('EmployeesService', ['$http', function ($http) {
return {
name: 'Employees Service',
getByTerm: function (params, callback) {
var terms = [];
//params example: {param1: "lorem", param2:"ipsum"}
for(var key in params){
if(params.hasOwnProperty(key)){
terms.push(key + "=" + params[key]);
}
}
//terms now looks like this: ["param1=lorem", "param2=ipsum"]
var url = 'Services/GetEmployess?' + terms.join("&");
//url will look lik this: 'Services/GetEmployess?param1=lorem¶m1=ipsum';
$http.get(url).success(function (data) {
callback(data);
});
}
};
} ]);
If you want the actual url that you're posting to be dynamic, pass it in as another parameter:
angular.module('myApp.services', [])
.factory('EmployeesService', ['$http', function ($http) {
return {
name: 'Employees Service',
getByTerm: function (url, term, callback) {
$http.get(url+term).success(function (data) {
callback(data);
});
}
};
} ]);
If neither of these are what you're looking for... can you elaborate on what part of the url you want to be dynamic?