Reputation: 97
I'm trying my hand at making api calls with Angular js. Unfortunately, I seem to be having some trouble. I am trying to pass a hero name into a form field and use that information to converse with my backend api. Unfortunately, I'm not getting any response data when I try to make contact. Any tips on how to make a successful call?
Here is the controller.
vm.errorMsg = '';
vm.hero = '';
function getCharacter(hero) {
$http({
method: "GET",
data: {
format: 'json'
},
url: "localhost:8080/character/heroByName/" + hero
}).then(function mySuccess(response){
vm.hero = response.data;
console.log(vm.hero);
}, function myError(response){
vm.errorMsg = response.statusText;
console.log(vm.errorMsg);
});
}
Here is the form field, where you can enter a hero name.
<div class="container">
<h2>{{character.title}}</h2>
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="input-group">
<input type="text" class="form-control" placeholder="Wolverine" ng-model="character.hero">
<span class="input-group-btn">
<button class="btn btn-default" type="submit" ng-click="character.getCharacter(character.hero)">Go!</button>
</span>
</div>
</div>
</div>
</div>
Upvotes: 3
Views: 134
Reputation: 2341
You should expose your function to the scope by assigning it to vm.getCharacter
. Afterwards you can call it in your template via ng-click="vm.getCharacter(character.hero)"
.
Controller
vm.errorMsg = '';
vm.hero = '';
vm.getCharacter = getCharacter;
function getCharacter(hero) {
$http({
method: "GET",
data: {
format: 'json'
},
url: "localhost:8080/character/heroByName/" + hero
}).then(function mySuccess(response){
vm.hero = response.data;
console.log(vm.hero);
}, function myError(response){
vm.errorMsg = response.statusText;
console.log(vm.errorMsg);
});
}
Template
<button class="btn btn-default" type="submit" ng-click="vm.getCharacter(character.hero)">Go!</button>
Upvotes: 2