3

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>
1
  • turn on debugging tools in your browser and show the actual error. Second ng-click="character.getCharacter(character.hero)" - character is a controllerAs ? Commented May 21, 2016 at 20:40

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.